React SetState不调用渲染 [英] React SetState doesn't call render

查看:95
本文介绍了React SetState不调用渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将我的函数发送给子组件以进行 callBack .在父级中,我有一个具有 setState 方法的函数:

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

其中状态是对象.

此后,设置状态.我可以在下一个 callBack 上看到它,在这里可以打印到控制台.但是,不会调用 render 方法.在 componentMount 期间,所有内容均正确呈现.

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.

该怎么办?谢谢.

推荐答案

当您执行 let oldStates = this.state.states; 时,您只是在创建 oldStates 变量对 this.state.states 的引用,因此在调用 setState 之前,您可以有效地更改状态.

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.

请尝试制作一个副本,例如 let oldStates = Object.assign({},this.state.states ,或使用

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.

这篇关于React SetState不调用渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆