在 componentDidMount() 上设置状态 [英] Setting state on componentDidMount()
问题描述
我知道在 componentDidMount
上设置状态是一种反模式,应该在 componentWillMount
上设置状态,但假设我想设置数字的长度li
标签作为一个状态.在这种情况下,我无法在 componentWillMount
上设置状态,因为在该阶段可能尚未安装 li
标记.那么,这里最好的选择应该是什么?如果我在 componentDidMount
上设置状态可以吗?
I know that it is an anti-pattern to set state on componentDidMount
and a state should be set on componentWillMount
but suppose I want to set the length of the number of li
tags as a state. In that case, I can't set the state on componentWillMount
since the li
tags might not have been mounted during that phase. So, what should be the best option here? Will it be fine if I set the state on componentDidMount
?
推荐答案
在 componentDidMount
中调用 setState
不是反模式.事实上,ReactJS 在他们的文档中提供了一个例子:
It is not an anti-pattern to call setState
in componentDidMount
. In fact, ReactJS provides an example of this in their documentation:
您应该在 componentDidMount 生命周期方法中使用 AJAX 调用填充数据.这样您就可以在检索数据时使用 setState 来更新您的组件.
You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.
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
});
}
)
}
这篇关于在 componentDidMount() 上设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!