react mobx 其他组件无法响应当前组件的action事件

发布于 2022-09-11 22:41:38 字数 1638 浏览 25 评论 0

我点击按钮,去更新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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

关于从前 2022-09-18 22:41:38

this.user = Object.assign(this.user,newUser)这个改一下
this.user = Object.assign(newUser,this.user)
这样试试

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文