componentDidMount()
中对服务器进行API调用或任何调用。将组件安装到DOM后调用此方法。此处对setState()
任何调用都将触发组件的重新呈现。在此方法中调用API并使用API返回的数据设置状态时,一旦收到数据,它将自动触发更新。 componentDidMount()
有一个模拟API调用。它在2.5秒后设置状态以模拟调用服务器以检索数据。此示例请求站点的当前活动用户总数。在render方法中,在h1
呈现activeUsers
的值。观看预览中发生的事情,并随时更改超时以查看不同的效果。 MyComponent
应该呈现一个包含h1
标记的div
元素。
testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return (mockedComponent.find("div").length === 1 && mockedComponent.find("h1").length === 1); })(), "MyComponent
should render a div
element which wraps an h1
tag.");'
- text: 应使用componentDidMount
的超时函数更新组件状态。
testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return new RegExp("setTimeout(.|\n)+setState(.|\n)+activeUsers").test(String(mockedComponent.instance().componentDidMount)); })(), "Component state should be updated with a timeout function in componentDidMount
.");'
- text: h1
标记应该从MyComponent
的状态呈现activeUsers
值。
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()), "The h1
tag should render the activeUsers
value from MyComponent
's state."); }; '
```