我有一个具有可观察属性的组件:
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
。但是我可以在呈现的代码中看到颜色确实在商店中发生了变化。