将React Router的道具与MobX商店同步

问题描述 投票:1回答:1

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

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

当它在他自己的组件中时,这是有效的。 但在我的情况下,我正在运行mobx商店的行动。 然后,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);
      });
  };
reactjs mobx
1个回答
1
投票

实现它的一种方法是使用history库中的createBrowserHistory函数手动创建history对象,并将此对象赋予history组件的Router prop。

然后,您可以在应用程序中的任何位置使用此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")
);
© www.soinside.com 2019 - 2024. All rights reserved.