react redux ,nextProps和this.props拿到的数据是相同的

项目里使用,react redux ,发现在componentWillReceiveProps中 ,nextProps和this.props拿到的数据是相同的,不是在render阶段nextProps的值才会赋给this.props吗?

我在reducer里面这么写的:

  let newState = {};
  Object.assign(newState, state);
  return newState;

这是个新对象了吧,不然只修改原来state的属性的话,组件是不会update的!

阅读 9k
4 个回答

说明传过来的 props 就是相同的呗。

不是在render阶段nextProps的值才会赋给this.props吗

不是的,是在 componentWillReceiveProps 或者 shouldComponentUpdatehttps://github.com/facebook/r...

componentWillReceiveProps 不管你的值有没有变都会触发。如果你的代码木有问题的话。那就应该是你使用的是 mutable 数据的问题了。
父组件的 state 值应该是Immutable 的,或者是通过 deepcopy 赋值,而不是用普通的变量赋值。

比如下面这种写法,就有可能造成nextprops 和 this.props 相等

var data = this.state.data;
data.name = '呵呵';
this.setState({
    data: data
});

正常应该这样写(Immutable):

this.setState({

data: this.state.data.update('name', 'hehe');

})

贴代码,你的情况和官方文档的描述不符,应该怀疑你的代码有问题
或者你是不是应该怀疑你的store中的数据本来就没有更新

nextprops赋值给this.props需要手动来赋值。componentwillreceiveprops通常在这个函数里做新旧数据的对比,从而自行决定需不需要setstate以及哪些数据需要setstate

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题