我知道设置状态是一种反模式,componentDidMount
并且应该设置状态,componentWillMount
但是假设我想将li
标签数量的长度设置为状态.在这种情况下,我无法设置状态,componentWillMount
因为li
在该阶段期间可能尚未安装标记.那么,这里最好的选择是什么?如果我设置状态会componentDidMount
好吗?
lux*_*lux 72
这不是一个反模式调用setState
在componentDidMount
.事实上,ReactJS在他们的文档中提供了这样的示例:
您应该在componentDidMount生命周期方法中使用AJAX调用填充数据.这样您就可以在检索数据时使用setState更新组件.
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
});
}
)
}
Run Code Online (Sandbox Code Playgroud)
根据React文档,完全可以setState()
从componentDidMount()
函数内调用。
这将导致render()
被调用两次,这比仅调用一次效率低,但除此之外,它还可以。
您可以在这里找到文档:
https://reactjs.org/docs/react-component.html
以下是文档摘录:
您可以立即在componentDidMount()中调用setState()。它会触发额外的渲染,但是会在浏览器更新屏幕之前发生。这样可以保证即使在这种情况下render()将被调用两次,用户也不会看到中间状态。请谨慎使用此模式,因为它经常会导致性能问题...
归档时间: |
|
查看次数: |
83214 次 |
最近记录: |