繁体   English   中英

React不会在道具更改时重新渲染

[英]React doesn't rerender on props change

我有以下代码,目标是为ajax POST操作准备一些对象。 所以实际上我有几个<input/> ,为某些对象提供数据。 我只是简化了它,使其简短易懂。

var MyComponent = React.createClass({
    onChange (value) {
       var newValue = this.props.value;
       newValue.field = value;
       this.props.dispatch(setValue(newValue));
    },

    render: function () {
      return (
        <myOtherComponent>
           <div><input onChange={this.onChange}/></div>
           <div>this.props.value</div>
        </myOtherComponent>
              )
    }
});

我也有一个动作:

export function setValue(value) {
    return {
        type: 'VALUE',
        data: value
    }
};

减速器,其中包含:

case 'NEW_DOCTOR':
            return {
                ...state,
                value: action.data
            };

问题是当我这样做时this.props.dispatch(setValue(newValue)); ,尽管我在console.log看到reducer确实被触发,但<myOtherComponent>不会重新渲染。 所以我必须在this.props.dispatch(setValue(newValue));之后放置this.setState(this.state) this.props.dispatch(setValue(newValue)); ,那么它就会放弃。 我第二次看到这种行为,实际上无法弄清楚我在做什么错。 有什么线索吗?

不确定这是造成您问题的原因,但是在这段代码中:

onChange (value) {
  var newValue = this.props.value;
  newValue.field = value;
  this.props.dispatch(setValue(newValue));
},

您是在直接改变道具,这是不应该的。

由于newValue = this.props.value
语句newValue.field = value
也会改变this.props.value

暂无
暂无

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

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