React SetState doesn't call render

有些话、适合烂在心里 提交于 2019-12-10 23:39:57

问题


I send my function to child component for callBack. In the parent, I have a function with setState method:

onInputUpdated(id){
  var array = {};
  let char = id.slice(-1);
  console.log(this.state.states)
  switch(char){
    case 'a':
      array[id] = this.getY(ReactDOM.findDOMNode(this.refs[id].refs.inp).value);
      break;
    case 'b':
      array[id] = this.getX(ReactDOM.findDOMNode(this.refs[id].refs.inp).value);
      break;
  }

  let oldStates = this.state.states;
  oldStates[id] = array[id];

  this.setState({
    states: oldStates
  });
  console.log(oldStates);
}

Where states is an object.

After this, states is set. I can see it in the next callBack, where I have print to console. However, the render method isn't invoked. During componentMount, everything is rendered correctly.

What to do? Thanks.


回答1:


When you do let oldStates = this.state.states; you're just making oldStates variable a reference to this.state.states, so you're effectively changing the state before you call setState.

Try to make a copy of it instead, for example let oldStates = Object.assign({}, this.state.states, or use lodash or something similar if you need a deep clone.




回答2:


I think you are setting it and then settings it back again. Try and create a brand new instance of the object. Here is how to do it with underscore.

First make sure you run the following . . .

npm install --save underscore

And then import underscore . . .

import _ from 'underscore';

and then clone the object.

let oldStates = _.clone(this.state.states);


来源:https://stackoverflow.com/questions/38477917/react-setstate-doesnt-call-render

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!