简体   繁体   English

setState() 不会从我的代码中重新呈现

[英]setState() does not re-render from my code

I gave onClick event for 3 items.我为 3 个项目提供了 onClick 事件。
When I click the button, each button is going to call clickHandler and clickHandler calls changeSelect with event.target.id .当我按一下按钮,每个按钮会调用clickHandlerclickHandler调用changeSelectevent.target.id
In the function, I want to change state value by suing this.setState() and it works well.在函数中,我想通过this.setState()来更改state值,并且效果很好。
But the problem is, after I call this.setState() , it does not trigger render() .但问题是,在我调用this.setState() ,它不会触发render()
What is the problem with my code?我的代码有什么问题?

class About extends React.Component {
  state = {
    main: true,
    data1: false,
    data2: false
  };
  changeSelect = id => {
    if (id === "select1") {
      this.setState(current => {
        current.main = true;
        current.data1 = false;
        current.data2 = false;
      });
    } else if (id === "select2") {
      this.setState(current => {
        current.main = false;
        current.data1 = true;
        current.data2 = false;
      });
    } else if (id === "select3") {
      this.setState(current => {
        current.main = false;
        current.data1 = false;
        current.data2 = true;
      });
    }
  };
  clickHandler = event => {
    event.preventDefault();
    this.changeSelect(event.target.id);
  };
  render() {
    console.log('render called')
    console.log(this.state)
    return (
      <div>
        <section className="selects">
          <div
            id="select1"
            className="select"
            onClick={this.clickHandler}
          ></div>
          <div
            id="select2"
            className="select"
            onClick={this.clickHandler}
          ></div>
          <div
            id="select3"
            className="select"
            onClick={this.clickHandler}
          ></div>
        </section>
        <section className="about">
          {this.state.main ? (
            "hi"
          ) : this.state.data1 ? (
            "bye"
          ) : (
            "oh"
          )}
        </section>
      </div>
    );
  }
}

Do not mutate state -> return a new one不要改变状态 -> 返回一个新状态

changeSelect = id => {
  if (id === "select1") {
    this.setState(current => ({
      main: true,
      data1: false,
      data2: false,
    }));
  } else if (id === "select2") {
    this.setState(current => ({
      main: false,
      data1: true,
      data2: false,
    }));
  } else if (id === "select3") {
    this.setState(current => ({
      main: false,
      data1: false,
      data2:true,
    }));
  }
};

Note: if your next state doesn't depend on previous state value - you can omit function call and do it like that:注意:如果您的下一个状态不依赖于前一个状态值 - 您可以省略函数调用并这样做:

this.setState({
   main: false,
   data1: false,
   data2: true,
});

:) :)

When you use this syntax on setState you need to return your new state :当您在setState上使用此语法时,您需要returnstate

//You are not returning your state just assigning the values
this.setState(current => {
        current.main = true;
        current.data1 = false;
        current.data2 = false;
      });

Just modify the state this way只需以这种方式修改状态

this.setState({
        main:true,
        data1:false,
        data2:false,
      });

After looking into the code.查了一下代码之后。 The issue is how setState is being used mutating the state won't re-render and instead return a new state.问题是如何使用setState改变状态不会重新渲染而是返回一个新状态。

Here is the ref:这是参考:

if (id === "select1") {
    this.setState({
      main: true,
      data1: false,
      data2: false,
    });
}

Note: You are not making use of current so you can avoid the updater method of setState .注意:您没有使用current因此您可以避免setState的 updater 方法。

As previously said by @max, You're mutating the state, and your setState isn't Returning anything,正如@max 之前所说,您正在改变状态,而您的 setState 没有返回任何内容,

Your set State你设置的状态

this.setState(current => {
        current.main = false;
        current.data1 = true;
        current.data2 = false;
      });

I would re-write your code like this to reduce conditions我会像这样重写你的代码以减少条件

state = {
    select1: true,
    select2: false,
    select3: false
};

const defaultState = {
  select1: false,
  select2: false,
  select3: false
}

changeSelect = id => {
    this.setState({ ...defaultState, [id]: true });
};
  1. You can use key for re-rendering component if key changes.如果密钥更改,您可以使用密钥重新渲染组件。
  2. Use key as per your choice, i have used Math.random() for ex.根据您的选择使用密钥,例如我使用了 Math.random()。

======================================================================== ================================================== ======================

class App extends Component {
  state = {
    main: true,
    data1: false,
    data2: false,
    key:Math.random()
  };
changeSelect = id => {
    if (id === "select1") {
      this.setState(current => {
        current.main = true;
        current.data1 = false;
        current.data2 = false;
      });
    } else if (id === "select2") {
      this.setState(current => {
        current.main = false;
        current.data1 = true;
        current.data2 = false;
      });
    } else if (id === "select3") {
      this.setState(current => {
        current.main = false;
        current.data1 = false;
        current.data2 = true;
      });
    }
  this.setState({key:Math.random()})
  };

 render() {


    return (
      <div key={this.state.key}>
          {/*your code*/}
      </div>
    );
  }

}

export default App;

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

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