我知道这是一个反模式设定状态上componentDidMount和状态应该设置componentWillMount但是假设我想设置的号码长度li标记作为状态。在这种情况下,我无法将状态设置为开启,componentWillMount因为li在该阶段可能尚未安装标签。那么,这里最好的选择应该是什么?如果我将状态设置为 on 可以componentDidMount吗?
在 componentDidMount() 上设置状态
IT技术
reactjs
2021-04-21 11:22:41
3个回答
这不是一个反模式调用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
});
}
)
}
根据 React 文档,setState()从componentDidMount()函数内部调用是完全可以的。
它会导致render()被调用两次,这比只调用一次效率低,但除此之外它完全没问题。
您可以在此处找到文档:
https://reactjs.org/docs/react-component.html#componentdidmount
以下是文档的摘录:
您可以在 componentDidMount() 中立即调用 setState()。它会触发额外的渲染,但会在浏览器更新屏幕之前发生。这保证即使在这种情况下 render() 将被调用两次,用户也不会看到中间状态。请谨慎使用此模式,因为它通常会导致性能问题...
该棉短绒抱怨使用的唯一原因setState({..})中componentDidMount和componentDidUpdate是在组件渲染的setState立即导致组件重新呈现。但最重要的是要注意:在这些组件的生命周期内使用它并不是 React 中的反模式。
请看看这个问题。您将了解有关此主题的更多信息。感谢您阅读我的回答。