如何将this.state放入状态更改后不会更改的变量中

  • 本文关键字:变量 状态 this state reactjs
  • 更新时间 :
  • 英文 :


简单问题(我希望(我如何将this.state保存到var中,如果没有它,当this.state更改时它将更改?有了代码,问题就更清楚了

this.state={x: "123"}
function change(){
this.setState({x: "456")}
}

再次,我想把第一个状态放入var中,它永远不会改变,即使在我们使用change((之后有什么想法吗?

您可以将值存储在类构造函数的实例级变量中。

constructor(props) {
this.myPermanentState = {x: "123"};
this.state = {x: "123"};
}
// now calling change will not affect the value of `myPermanentState`
function change(){
this.setState({x: "456"});
console.log(this.myPermanentState);
}

如果您使用带有钩子的React 16,您可能可以使用useRef钩子来获得类似的结果。

您可以创建一个包含初始状态的变量,并将其值分配给this.state

const initialState = {x: "123"};
...
this.state = initialState;

最新更新