我知道将state设置为componentDidMount
是一种反模式,state应该设置为componentWillMount
,但是假设我想将li
个标签的长度设置为state.在这种情况下,我无法将状态设置为componentWillMount
,因为在该阶段可能没有安装li
个标记.那么,什么是最好的 Select 呢?如果我把州定在componentDidMount
,可以吗?
我知道将state设置为componentDidMount
是一种反模式,state应该设置为componentWillMount
,但是假设我想将li
个标签的长度设置为state.在这种情况下,我无法将状态设置为componentWillMount
,因为在该阶段可能没有安装li
个标记.那么,什么是最好的 Select 呢?如果我把州定在componentDidMount
,可以吗?
在componentDidMount
中调用setState
并不是一种反模式.事实上,ReactJS在their documentation中提供了一个例子:
您应该在componentDidMount生命周期方法中使用AJAX调用填充数据.这样,在检索数据时,您可以使用setState更新组件.
100
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
});
}
)
}