Javascript 清除状态 es6 React

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34845650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:56:31  来源:igfitidea点击:

Clearing state es6 React

javascriptreactjs

提问by Guy

I am trying to clear a components statebut can't find a reference for the es6 syntax. I was using:

我正在尝试清除组件,state但找不到 es6 语法的参考。我正在使用:

this.replaceState(this.getInitialState());

this.replaceState(this.getInitialState());

however this does not work with the es6 class syntax.

但是这不适用于 es6 类语法。

How would I achieve the same result?

我将如何达到相同的结果?

回答by David L. Walsh

To the best of my knowledge, React components don't keep a copy of the initial state, so you'll just have to do it yourself.

据我所知,React 组件不会保留初始状态的副本,因此您只需要自己完成即可。

const initialState = {
    /* etc */
};

class MyComponent extends Component {
    constructor(props) {
        super(props)
        this.state = initialState;
    }
    reset() {
        this.setState(initialState);
    }
    /* etc */
}

Beware that the line this.state = initialState;requires you never to mutate your state, otherwise you'll pollute initialStateand make a reset impossible. If you can't avoid mutations, then you'll need to create a copy of initialStatein the constructor. (Or make initialStatea function, as per getInitialState().)

请注意,该行this.state = initialState;要求您永远不要改变您的状态,否则您会污染initialState并无法重置。如果无法避免突变,则需要initialState在构造函数中创建一个副本。(或者initialState按照getInitialState().)

Finally, I'd recommend you use setState()and not replaceState().

最后,我建议您使用setState()而不是replaceState().

回答by RaptoX

Problem

问题

The accepted answer:

接受的答案

const initialState = {
    /* etc */
};

class MyComponent extends Component {
    constructor(props) {
        super(props)
        this.state = initialState;
    }
    reset() {
        this.setState(initialState);
    }
    /* etc */
}

unfortunately is not correct.

不幸的是不正确

initialStateis passed as a reference to this.state, so whenever you change stateyou also change initialState(constdoesn't really matter here). The result is that you can never go back to initialState.

initialState作为对 的引用传递this.state,因此每当您更改时,state您也会更改initialStateconst在这里并不重要)。结果是你再也回不去了initialState

Solution

解决方案

You have to deep copyinitialStateto state, then it will work. Either write a deep copy function yourself or use some existing module like this.

你必须深度复制initialStatestate,然后它会起作用。要么自己写一个深拷贝函数,要么像这样使用一些现有的模块。

回答by Eruz Apodaca

This is the solution implemented as a function:

这是作为函数实现的解决方案:

Class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = this.getInitialState();
  }

  getInitialState = () => ({
    /* state props */
  })

  resetState = () => {
     this.setState(this.getInitialState());
  }
}

回答by Charles Offenbacher

The solutions that involve setting this.statedirectly aren't working for me in React 16, so here is what I did to reset each key:

this.state直接涉及设置的解决方案在 React 16 中对我不起作用,所以这是我为重置每个键所做的:

  const initialState = { example: 'example' }
  ...
  constructor() {
      super()
      this.state = initialState
  }
  ...
  reset() {
    const keys = Object.keys(this.state)
    const stateReset = keys.reduce((acc, v) => ({ ...acc, [v]: undefined }), {})
    this.setState({ ...stateReset, ...initialState })
  }

回答by Balanced02

First, you'll need to store your initial state when using the componentWillMount()function from the component lifecycle:

首先,在使用componentWillMount()组件生命周期中的函数时,您需要存储初始状态:

componentWillMount() {
    this.initialState = this.state
}

This stores your initial state and can be used to reset the state whenever you need by calling

这会存储您的初始状态,并可用于在您需要时通过调用重置状态

this.setState(this.initialState)

回答by uke5tar

const initialState = {
    a: '',
    b: '',
    c: ''
};

class ExampleComponent extends Component {
    state = { ...initialState } // use spread operator to avoid mutation
    handleReset = this.handleReset.bind(this);

    handleReset() {
         this.setState(initialState);
    }
 }

Remember that in order to be able to reset the state it is important not to mutate initialState.

请记住,为了能够重置状态,重要的是不要改变initialState。

state = {...initialState} // GOOD 
// => state points to a new obj in memory which has the values of initialState

state = initialState // BAD 
// => they point to the same obj in memory

The most convenient way would be to use ES6 Spread Operator. But you could also use Object.assign instead. They would both achieve the same.

最方便的方法是使用 ES6 扩展运算符。但您也可以改用 Object.assign。他们都会达到同样的目的。

state = Object.assign({}, initialState); // GOOD
state = {...initialState}; // GOOD

回答by Goran Jakovljevic

In most cases you dont need a deep copy, rarely initial state is object of objects, so using spread operator which babel transpiles to the object.assign should be fine.

在大多数情况下,您不需要深拷贝,很少有初始状态是对象的对象,因此使用将 babel 转换为 object.assign 的扩展运算符应该没问题。

So, inside constructor you would have:

因此,在构造函数中,您将拥有:

    class MyComponent extends Component {
        constructor(props) {
            super(props)
            this.state = {
                key: value,
                key2: value
            }
            this.initialState = { ...this.state } 
        }
    }

From there you can use

从那里你可以使用

this.setState(this.initialState);

to reset. But if for some reason your initial state is more complex object, use some library.

重置。但是如果由于某种原因您的初始状态是更复杂的对象,请使用一些库。

回答by eveevans

This is how I handle it:

我是这样处理的:

class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this._initState = {
        a: 1,
        b: 2
      }
    this.state = this._initState;
  }

  _resetState(){
     this.setState(this._initState);
   }
}

Update:Actually this is wrong. For future readers please refer to @RaptoX answer. Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.

更新:实际上这是错误的。对于未来的读者,请参阅@RaptoX 答案。此外,您可以使用不可变库来防止由引用分配引起的奇怪状态修改。

回答by Brian Loughnane

I will add to the above answer that the reset function should also assign state like so:

我将在上面的答案中补充说重置功能也应该像这样分配状态:

reset() {
  this.state = initialState;
  this.setState(initialState);
}

The reason being that if your state picks up a property that wasn't in the initial state, that key/value won't be cleared out, as setState just updates existing keys. Assignment is not enough to get the component to re-render, so include the setState call as well -- you could even get away with this.setState({}) after the assignment.

原因是如果您的状态选择了一个不在初始状态的属性,则该键/值不会被清除,因为 setState 只是更新现有键。赋值不足以让组件重新渲染,所以也包括 setState 调用——你甚至可以在赋值之后使用 this.setState({}) 。

回答by SColvin

In some circumstances, it's sufficient to just set all values of stateto null.

在某些情况下,只需将 的所有值设置为 就足够statenull

If you're state is updated in such a way, that you don't know what might be in there, you might want to use

如果您的状态以这种方式更新,您不知道那里可能有什么,您可能想要使用

this.setState(Object.assign(...Object.keys(this.state).map(k => ({[k]: null}))))

Which will change the state as follows

这将改变状态如下

{foo: 1, bar: 2, spam: "whatever"} > {foo: null, bar: null, spam: null}

Not a solution in all cases, but works well for me.

不是所有情况下的解决方案,但对我来说效果很好。