React.JS备份状态的最佳方法

时间:2019-12-03 04:02:18

标签: 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){
        theState = {...theState,...data}
        console.log('sate update',{theState})
        this.setState(theState)
    }
}

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

1 个答案:

答案 0 :(得分:0)

要在基于类的组件中使用状态,您需要使用构造函数,然后使用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这样的应用程序状态管理器。