Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React.JS备份状态的最佳方式_Javascript_Reactjs_React State Management_React State - Fatal编程技术网

Javascript React.JS备份状态的最佳方式

Javascript React.JS备份状态的最佳方式,javascript,reactjs,react-state-management,react-state,Javascript,Reactjs,React State Management,React State,在我的应用程序中,当呈现组件时,我的状态不知何故会被破坏,因此我将状态放置在类之外,并将每个setState更改为我自己定义的更改状态的方法 这是我的密码 let theState = {//the state properties} class Foo extends Component{ //the method is used to change the state, and setState to trigger rendering updateState(data){

在我的应用程序中,当呈现组件时,我的状态不知何故会被破坏,因此我将状态放置在类之外,并将每个
setState
更改为我自己定义的更改状态的方法

这是我的密码

let theState = {//the state properties}
class Foo extends Component{
  //the method is used to change the state, and setState to trigger rendering
  updateState(data){
        theState = {...theState,...data}
        console.log('sate update',{theState})
        this.setState(theState)
    }
}

这没关系,但问题是当我们谈论可重用性时,我不想在每个组件上都编写
updateState
方法,有没有更好的解决方案?

要在基于类的组件中使用状态,需要使用构造函数,然后使用
this.state={}
。然后可以通过在组件中调用
this.setState({})
来更新状态。例如:

class Something extends React.Component {
  constructor(props) {
    super(props);
    this.state = {foo: "thing"};
  }
或者,如果您使用的是React^16,则可以使用功能组件和React挂钩。在这种情况下,您的代码看起来像:

const Foo = () -> {
  const [data, setdata] = React.useState()

  const updateState = (update) => {
    setData({...data, ...update}) //assuming it is an update or
    setData({update}) //assuming you want to replace the values
  }

}

状态仅适用于本地(组件)级别,除非引入应用程序状态管理器(如Redux)。

使用基于函数的react组件作为useEffect。在易于处理此场景的地方,您可以使用钩子重复使用状态登录,检查此链接您可以发布更多代码,以便我们可以尝试诊断状态消失的原因吗?您不必像这样手动备份状态。@Tim我正在与一个团队合作,因此我的一名团队成员将codabase从基于组件更改为基于react hooks,我不想使用functional component重构几乎所有的代码