我想在注册失败时重定向。 我正在使用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);
});
};
实现它的一种方法是使用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")
);