这不是一个反模式调用
setState在
componentDidMount。实际上,ReactJS在其文档中提供了一个示例:
您应该在componentDidMount生命周期方法中使用AJAX调用填充数据。这样一来,您可以在检索数据时使用setState更新组件。
Doc中的示例
componentDidMount() { fetch("https://api.example.com/items") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, items: result.items }); }, // Note: it's important to handle errors here // instead of a catch() block so that we don't swallow // exceptions from actual bugs in components. (error) => { this.setState({ isLoaded: true, error }); } ) }


