1

我有一个具有可观察属性的组件:

class Store {
   @observable color = "red" 
}

const store = new Store(); 

@observer
class MyComponent extends React.Component {  
  componentWillReceiveProps(nextProps) {
    // Not called!
    console.log("Component will receive props", nextProps.store.color)
  }
  componentDidMount() {
    console.log("Component did mount", this.props.store.color)  
  }
  changeColor = () => {
    this.props.store.color = (this.props.store.color==="red")? "blue":"red";
  };
  render() {
    return <div>
        color: {this.props.store.color}  
        <button onClick={this.changeColor}>Change color</button>   
    </div>
  }
};

ReactDOM.render(<MyComponent store={store} />, document.body)

我的问题是,componentWillReceiveProps当观察到的变量发生变化时(通过单击按钮),它永远不会被调用,componentDidReceiveProps也不会被调用shouldComponentUpdate。但是我可以在呈现的代码中看到颜色确实在商店中发生了变化。

4

2 回答 2

4

tl;博士:使用componentWillUpdatecomponentDidUpdate


作为道具传递的对象Store永远不会改变,即使它的内容发生了变化。使用的技巧@observable是它会在不改变 props 的情况下触发组件中的更新。因此,使用诸如 和 之类的生命周期函数shouldComponentUpdatecomponentWillReceiveProps无法componentDidReceiveProps使用,因为它们会在组件的道具或状态更改时触发。mobx 文档在该shouldComponentUpdate部分中很好地解释了它。

因此,要在 observable 中捕获更新,我们必须深入了解生命周期堆栈并使用componentWillUpdateand componentDidUpdate

因此,代码应如下所示:

@observer
class MyComponent extends React.Component {  
  componentWillReceiveProps(nextProps) {
    // Not called! 
    console.log("Component will receive props", nextProps.store.color)
  }
  componentWillUpdate(nextProps) {
    console.log("Component will update", nextProps.store.color)
  }
  componentDidMount() {
    console.log("Component did mount", this.props.store.color)  
  }
  changeColor = () => {
    this.props.store.color = (this.props.store.color==="red")? "blue":"red";
  };
  render() {
    return <div>
        color: {this.props.store.color}  
        <button onClick={this.changeColor}>Change color</button>   
    </div>
  }
};

JS 斌: http: //jsbin.com/voqugezaya/edit ?js,console,output

在幕后,mobx-react使用该forceUpdate函数触发组件重新渲染,而不必更改其 props 中的对象(仅更改其内容)。

另外,mobx 还引入了一个新功能,对调试很有帮助:componentWillReact.

于 2017-01-19T07:55:56.483 回答
0

是否应该使用 mobx 生命周期钩子函数?(例如:componentWillReact)。请参阅https://mobx.js.org/refguide/observer-component.html上的文档

于 2017-01-23T16:04:26.403 回答