react mobx 其他组件无法响应当前组件的action事件
我点击按钮,去更新store里的状态,组件一能响应变化,组件二就无法响应变化了,为什么?
1.component one
@inject("store")
@observer
class MyComponentOne extends React.Component{
constructor (props){
super(props);
console.log(this.props,"props");
this.test = this.test.bind(this);
}
render() {
console.log(‘render in one’);
return (
<div>
<button onClick={this.test}>click to update</button>
1111{this.props.store.user.name}111
</div>
);
}
test(){
let u = {
name:’my new name'
}
this.props.store.updateUser(u);
}
};
2.component two
@inject("store")
@observer
class MyComponentTwo extends React.Component{
constructor (props){
super(props);
console.log(this.props,"props");
}
render() {
console.log(‘render in two’);
return (
<div>
222{this.props.store.user.name}222
</div>
);
}
};
3.store.js
class StoreClass{
@observable
user = {
name:’my old name',
};
@action.bound
updateUser(newUser){
this.user = Object.assign(this.user,newUser);
}
}
4._app.js (use in nextjs)
class Home extends App {
state = {
store: new Store(),
}
render () {
const { Component, pageProps } = this.props;
return (
<Provider store={this.state.store}>
<Component {...pageProps} />
</Provider>
)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
this.user = Object.assign(this.user,newUser)这个改一下
this.user = Object.assign(newUser,this.user)
这样试试