将 React Router 的 props 与 MobX Store 同步

sync React Router’s props with a MobX Store

我想在注册失败时重定向。
我正在使用 Mobx。
所以有一个关于这个的问题。
当我搜索重定向时,人们说使用下面的代码。

this.props.history.push("/");

这在他自己的组件中有效。
但就我而言,我是 运行 mobx store 的内部操作。
然后, this.props 不是路由组件的道具。
所以我想知道如何通过 mobx 存储读取路由历史记录。
非常感谢!

// In the mobx store

 @action submitSignIn = () => {
    axios
      .post('auth/join', { email: this.initialState.register.email })
      .then((response) => {
        if (response.data === true) {
          this.props.history.push('/signin');
        }
      .catch((error) => {
        console.log(error);
      });
  };

一种解决方法是使用 createBrowserHistory function from the history library, and give this object to the history prop of the Router 组件手动创建一个 history 对象。

然后,您可以在应用程序中的任意位置使用此 history 对象以编程方式控制路由。

例子

import { createBrowserHistory } from "history";
import { Router } from "react-router-dom";

const history = createBrowserHistory();

class Store {
  // ...

  @action submitSignIn = () => {
    axios
      .post("auth/join", { email: this.initialState.register.email })
      .then(response => {
        if (response.data === true) {
          history.push("/signin");
        }
      })
      .catch(error => {
        console.log(error);
      });
  };
}

ReactDOM.render(
  <Router history={history}>
    <App />
  </Router>,
  document.getElementById("app")
);