【问题标题】:Reset component state in React在 React 中重置组件状态
【发布时间】:2019-01-20 16:17:14
【问题描述】:

我真的很难使用 React 中的方法将状态重置为原始状态。我当前的重置方法仅重置该值。我曾尝试添加等于原始状态的 const,然后将状态设置为等于该状态,但我没有运气。

有什么建议吗?

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 });
  };
}

【问题讨论】:

  • 这是一个无效的 JS 代码。请看括号。

标签: javascript reactjs state


【解决方案1】:

您可以将初始状态保存在单独的数组中,并创建一个数组的副本作为初始状态,并在使用handleReset 时创建一个数组的副本。

示例

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>

【讨论】:

  • 谢谢。我应该知道这一点。我试图将 counters 数组放在 handleReset 方法中,而不是全局放置。你知道为什么当我把它放在方法中时它不起作用吗?编辑:没关系,它实际上工作得很好。我一定有语法错误或什么的。无论如何,谢谢你的代码。它解决了我的问题。
【解决方案2】:

很多人都不知道,更改 key 属性是重置组件状态的一种方法。当元素的key 发生变化时,React 将卸载它并重新实例化该组件。

如果您的组件有一个父组件并且可以让父组件更改您组件上的key。在下面的示例中,父组件的key 状态是一个数字。当点击reset按钮时,父组件增加keyCounter组件被重新挂载,从而清除所有状态。 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>

【讨论】:

    【解决方案3】:

    假设您的状态是有效的 JSON,这似乎是一个简单的解决方案:

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

    深度克隆,无需库,原生代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 2019-02-17
      • 2021-01-06
      • 1970-01-01
      相关资源
      最近更新 更多