gpt4 book ai didi

reactjs - 在 componentDidMount() 上设置状态

转载 作者:行者123 更新时间:2023-12-03 12:54:47 25 4
gpt4 key购买 nike

我知道在 componentDidMount 上设置状态是一种反模式,并且应该在 componentWillMount 上设置状态,但假设我想设置数字的长度作为状态的 li 标签。在这种情况下,我无法在 componentWillMount 上设置状态,因为 li 标签在该阶段可能尚未安装。那么,这里最好的选择应该是什么?如果我在 componentDidMount 上设置状态可以吗?

最佳答案

componentDidMount 中调用 setState 并不是反模式。事实上,ReactJS 在their documentation 中提供了一个这样的例子。 :

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.

<强> Example From 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
});
}
)
}

关于reactjs - 在 componentDidMount() 上设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35850118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com