本文介绍了缺点直接改变状态和forceUpdate()vs setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反应文档说永远不要直接改变this.state,因为之后调用setState()可能会替换你所做的突变。把this.state看作是不可变的...... 但是当我根本不使用setState()时这是一个非问题。

React docs say Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable... But this is a non issue when I don't use setState() at all.

我能想到的唯一缺点是:

The only disadvantages I can think of are:


  • 不能使用 shouldComponentUpdate / componentWillUpdate / componentDidUpdate 比较旧状态和新状态。

  • Can't use shouldComponentUpdate/componentWillUpdate/componentDidUpdate to compare old and new state.

对于其他人来说,可能会使维护更加困难。因为它不是做事的标准方式。

Will probably make maintainability harder for others working on it. Since it's not the standard way to do things.

但是没有使用setState()和直接改变状态的其他缺点?

But are there any other disadvantages to not using setState() and mutating state directly?

编辑:我删除了我的理由为什么我被这个想法所吸引。我知道这是一种反模式,我知道这可能不是最好的方式。但这个问题都是关于为什么的问题。

I've deleted my reasoning why I'm attracted to that idea. I know it's an anti-pattern and I know it's probably not the best way to do it. But this question is all about "why".

EDIT2:这里的关键词也是其他 in ...还有其他缺点......

Also key word here is other in ... are there any other disadvantages ...

推荐答案

你不应该直接改变状态。 setState的异步性质有办法解决它。 setState 提供您可以使用的回调

You should not directly mutate the state. Async nature of setState has ways to get around it. setState provides a callback that you can use.

此外,forceUpdate完全绕过 shouldComponentUpdate ,这不是一个好的模式,尤其是在使用 React.PureComponent 进行浅层比较时你的道具。

Also forceUpdate completely bypasses the shouldComponentUpdate which is not a good pattern especially when using React.PureComponent that does a shallow comparison of your props.

此外,您不应该使用反模式,而是尝试按照文档建议的正确方式解决您的问题

Also you should not use anti patterns, rather try to solve your issues the correct way suggested by the docs

直接设置缺陷状态是React的生命周期
方法 - shouldComponentUpdate() componentWillUpdate()
componentDidUpdate() - 取决于使用
<$ c $调用的状态转换C>的setState()。如果直接更改状态并使用
调用 setState()空对象,则无法再实现这些方法。

A drawback setting state directly is that React's lifecycle methods - shouldComponentUpdate(), componentWillUpdate(), componentDidUpdate() - depend on state transitions being called with setState(). If you change the state directly and call setState() with an empty object, you can no longer implement those methods.

此外,您可能知道您的代码与React交互的方式是这些覆盖或其他问题不会发生但您正在创建其他情况当他们开始遵循正确的方法时,开发人员或未来的更新会突然发现自己有奇怪或微妙的问题

Also You may know personally that your code interacts with React in such a way that these over-writes or other issues can't happen but you're creating a situation where other developers or future updates can suddenly find themselves with weird or subtle issues when they start following the right approach

使用setState来改变状态

Using setState to mutate state

class App extends React.Component {
  state =  {
      counter: 0
  }
  updateCounter = () => {
    this.setState(prevState => ({counter: prevState.counter + 1}));
  }
  componentWillUpdate(nextProps, nextState){
    console.log(this.state.counter === nextState.counter);
  }
  
  componentDidUpdate(prevProps, prevState) {
     console.log(this.state.counter === prevState.counter);
  }
  render() {
      return (
        <div>
          {this.state.counter}
          <button onClick={this.updateCounter}>Increment</button>
        </div>
      )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<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="app"></div>

直接改变状态

Directly mutating state

class App extends React.Component {
  state =  {
      counter: 0
  }
  updateCounter = () => {
    this.state.counter =  this.state.counter + 1;
    this.forceUpdate();
  }
  componentWillUpdate(nextProps, nextState){
    console.log(this.state.counter === nextState.counter);
  }
  
  componentDidUpdate(prevProps, prevState) {
     console.log(this.state.counter === prevState.counter);
  }
  render() {
      return (
        <div>
          {this.state.counter}
          <button onClick={this.updateCounter}>Increment</button>
        </div>
      )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<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="app"></div>

这篇关于缺点直接改变状态和forceUpdate()vs setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 16:19