search and replace ```\n< with ```\n\n< to ensure there's an empty line before closing tags
3.0 KiB
3.0 KiB
id, title, challengeType, isRequired, videoUrl, localeTitle
| id | title | challengeType | isRequired | videoUrl | localeTitle |
|---|---|---|---|---|---|
| 5a24c314108439a4d403617d | Use the Lifecycle Method componentDidMount | 6 | false | 使用生命周期方法componentDidMount |
Description
componentDidMount()中对服务器进行API调用或任何调用。将组件安装到DOM后调用此方法。此处对setState()任何调用都将触发组件的重新呈现。在此方法中调用API并使用API返回的数据设置状态时,一旦收到数据,它将自动触发更新。 Instructions
componentDidMount()有一个模拟API调用。它在2.5秒后设置状态以模拟调用服务器以检索数据。此示例请求站点的当前活动用户总数。在render方法中,在h1呈现activeUsers的值。观看预览中发生的事情,并随时更改超时以查看不同的效果。 Tests
tests:
- text: <code>MyComponent</code>应该呈现一个包含<code>h1</code>标记的<code>div</code>元素。
testString: assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return (mockedComponent.find('div').length === 1 && mockedComponent.find('h1').length === 1); })());
- text: 应使用<code>componentDidMount</code>的超时函数更新组件状态。
testString: assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return new RegExp('setTimeout(.|\n)+setState(.|\n)+activeUsers').test(String(mockedComponent.instance().componentDidMount)); })());
- text: <code>h1</code>标记应该从<code>MyComponent</code>的状态呈现<code>activeUsers</code>值。
testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ activeUsers: 1237 }); return mockedComponent.find(''h1'').text(); }; const second = () => { mockedComponent.setState({ activeUsers: 1000 }); return mockedComponent.find(''h1'').text(); }; assert(new RegExp(''1237'').test(first()) && new RegExp(''1000'').test(second())); }; '
Challenge Seed
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
activeUsers: null
};
}
componentDidMount() {
setTimeout( () => {
this.setState({
activeUsers: 1273
});
}, 2500);
}
render() {
return (
<div>
<h1>Active Users: { /* change code here */ }</h1>
</div>
);
}
};
After Test
console.info('after the test');
Solution
// solution required
/section>