【发布时间】:2024-04-20 03:25:01
【问题描述】:
我一直在使用 React 状态来维护一些数据。对于整数和字符串,它运行良好,但不幸的是数组无法运行。
在我的组件构造函数中,我有
constructor(props) {
super(props);
this.state = {
terms: 5,
myArray: []
}
然后,我试图在 componentDidUpdate 中维护它
componentDidUpdate() {
this.state = {
terms: this.state.terms,
myArray: this.state.myArray
}
但myArray: this.state.myArray 不起作用。但是terms: this.state.terms 运行良好。
有人可以帮忙吗!
【问题讨论】:
-
为什么要在componentDidUpdate方法中设置状态??还有一件事你说不工作是什么意思,你试图更新数组?
-
你也应该使用 this.setState() 来更新状态
-
渲染组件后,我必须更改其他状态值。
-
@ Mayank Shukla 实际上,由于某种原因,我正在重新初始化状态,无论如何没关系。我解决了我的问题。不过感谢您及时的回复。我真的很感激。
标签: javascript reactjs react-redux