当观察到更改时,React Mobx componentDidUpdate不更新

Ibr*_*ady 3 reactjs mobx mobx-react

我是Mobx和reactjs的新手,我了解Redux和本机响应,并且在Redux中,当我习惯于调用动作并且道具得到更新时,componentDidUpdate生命周期方法会被触发。

我现在遇到的情况是登录。因此,用户填写表单,单击提交,然后提交调用Mobx操作(异步),并且服务器响应时,观察对象将更新,然后导航到主页(在组件中进行导航)。

这是我的商店代码。

import { autorun, observable, action, runInAction, computed, useStrict } from 'mobx';

useStrict(true);

class LoginStore {
    @observable authenticated = false;
    @observable token = '';

    @computed get isAuthenticated() { return this.authenticated; }


    @action login = async (credentials) => {
        const res = await window.swaggerClient.Auth.login(credentials)l
        // checking response for erros
        runInAction(() => {
            this.token = res.obj.token;
            this.authenticated = true;
        });
    }
}

const store = new LoginStore();

export default store;

export { LoginStore };
Run Code Online (Sandbox Code Playgroud)

这个处理程序在我的组件中

handleSubmit = (e) => {
        e.preventDefault();

        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.store.login(values);
            }
        });
    }

    componentDidUpdate() {
        if (this.props.store.isAuthenticated) {
            const cookies = new Cookies();
            cookies.set('_cookie_name', this.props.store.token);
            this.props.history.push('main');
        }
    }
Run Code Online (Sandbox Code Playgroud)

这不是理想的代码,我只是在做实验,但是我不太明白。

另外,如果我(isAuthenticated)render生命周期方法中使用计算值,componentDidUpdate则会触发,但是,如果我未在render方法中使用计算值,componentDidUpdate则不会触发。例如,如果我这样做

render() {
  if (this.props.store.isAuthenticated) return null
  // .... rest of the code here
}
Run Code Online (Sandbox Code Playgroud)

以上将触发componentDidUpdate。

我想念什么吗?Mobx有更好的方法吗?谢谢

Ali*_*lik 6

观察者组件将仅对其render方法中引用的可观察对象做出反应。MobX文档对此进行了介绍

我建议您使用它when来解决问题。

componentDidMount() {
  when(
    () => this.props.store.isAuthenticated,
    () => { 
      // put your navigation logic here
    }
  );
}
Run Code Online (Sandbox Code Playgroud)