我正在开发一个 React js 项目。我有一个状态变量,并在 componentDidMount()
方法期间使用另一个普通变量 (x
) 初始化该状态变量 (x_state
)。
但是每当我的普通变量 (x
) 更新时,它就会自动更新状态变量 (x_state
)。
export class Demo extends React.Component {
constructor(props) {
super(props);
this.state = {
x_state: null
}
this.x = {}
}
componentDidMount() {
this.setState({
x_state: this.x
})
}
}
局部变量 this.x 根据代码内的特定条件进行更新。每当局部变量 this.x 更新时,它都会自动更新状态变量 x_state。 如何防止自动更新或自动setstate方法调用
最佳答案
这是因为 x
是一个对象,并且您正在通过此代码设置引用
this.setState({
x_state: this.x
})
您应该使用Object.assign()
制作它的副本
this.setState({
x_state: Ojbect.assign({},this.x)
})
或者,如果 this.x
最初是一个嵌套对象,您可以使用 JSON.parse(JSON.stringify())
this.setState({
x_state: JSON.parse(JSON.stringify(this.x))
})
关于javascript - React js状态变量自动更新,无需setstate方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55204887/