简体   繁体   English

在 React 中重置组件 state

[英]Reset component state in React

I'm really struggling to reset the state back to it's orginal from with a method in React.我真的很难用 React 中的方法将 state 重置回原来的状态。 My current reset method only resets the value.我当前的重置方法仅重置该值。 I have tried adding in const equal to the original state and then setting state equal to that, but I have had no luck.我尝试添加等于原始 state 的 const,然后将 state 设置为等于那个,但我没有运气。

Any advice?有什么建议吗?

class App extends Component {
  state = {
    counters: [
      { id: 1, value: 4 },
      { id: 2, value: 0 },
      { id: 3, value: 0 },
      { id: 4, value: 0 }
    ]
  };

  handleReset = () => {
    const counters = this.state.counters.map(c => {
      c.value = 0;
      return c;
    });
    this.setState({ counters: counters });
  };
}

You could keep the initial state in a separate array, and create a copy of the array as initial state, and also create a copy of the array when using the handleReset . 您可以将初始状态保存在单独的数组中,并创建该数组的副本作为初始状态,并在使用handleReset时也创建该数组的副本。

Example

 const counters = [ { id: 1, value: 4 }, { id: 2, value: 0 }, { id: 3, value: 0 }, { id: 4, value: 0 } ]; class App extends React.Component { state = { counters: [...counters] }; handleReset = () => { this.setState({ counters: [...counters] }); }; handleClick = index => { this.setState(prevState => { const counters = [...prevState.counters]; counters[index] = { ...counters[index], value: counters[index].value + 1 }; return { counters }; }); }; render() { return ( <div> {this.state.counters.map((counter, index) => ( <button id={counter.id} onClick={() => this.handleClick(index)}> {counter.value} </button> ))} <div> <button onClick={this.handleReset}>Reset</button> </div> </div> ); } } ReactDOM.render(<App />, document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

Not known to many, changing the key prop is one way to reset a component's state. 许多人不知道,更改key道具是重置组件状态的一种方法。 When the key of an element changes, React will unmount it and reinstantiate the component. 当一个元素的key改变时,React将卸载它并重新实例化该组件。

If your component has a parent component and could get the parent component to change the key on your component. 如果您的组件具有父组件,并且可以获取父组件以更改组件上的key In the example below, the parent component has a key state that is a number. 在下面的示例中,父组件的key状态为数字。 When you click the reset button, the parent component increases the key and the Counter component is remounted, thereby clearing all state. 当您单击重置按钮时,父组件会增加key ,并且Counter组件会重新安装,从而清除所有状态。 Any different value of key will cause the component to remount. key任何不同值都将导致重新安装组件。

 class Counter extends React.Component { state = { counters: [ { id: 1, value: 4 }, { id: 2, value: 0 }, { id: 3, value: 0 }, { id: 4, value: 0 } ], }; handleClick = index => { this.setState(prevState => { const counters = [...prevState.counters]; counters[index] = { ...counters[index], value: counters[index].value + 1 }; return { counters }; }); }; render() { return ( <div> {this.state.counters.map((counter, index) => ( <button id={counter.id} onClick={() => this.handleClick(index)}> {counter.value} </button> ))} <div> <button onClick={this.props.handleReset}>Reset</button> </div> </div> ); } } class App extends React.Component { state = { key: 0, }; handleReset = () => { this.setState(prevState => ({ key: prevState.key + 1 })); }; render() { return ( <div> <Counter key={this.state.key} handleReset={this.handleReset} /> </div> ); } } ReactDOM.render(<App />, document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

With the assumption that your state is valid JSON, this seems a simple solution:假设您的 state 是有效的 JSON,这似乎是一个简单的解决方案:

const initialState = {...};

class ... {
    this.state = JSON.parse(JSON.stringify(initialState));

    reset = () => {
        this.setState(JSON.parse(JSON.stringify(initialState)));
    }
}

Deep cloning, no libs needed, native code.深度克隆,无需库,本地代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM