我正在使用react-router-dom v4.表单提交成功后如何重定向到页面?
const submit=({email='',password=''})=>{ let error={}; let isError=false; if(email.trim()===''){ error.email='required'; isError=true; } else if(![ 'test@wp.pl' ].includes(email)){ error.email='User does not exist'; isError=true; } if(password.trim()===''){ error.password='required'; isError=true; } else if(password!=='test'){ error.password='Wrong password'; isError=true; } if(isError){ throw new SubmissionError(error); } else{ //redirect to new page } }
在评论的地方应该有一个重定向功能,但我不知道如何做到这一点.我试过放在那里:
< Redirect to =“/ pageAfterSubmit”push />但什么都没发生.
我在index.js中的浏览器路由器如下所示:
<BrowserRouter > <Provider store={store}> <div> <Route path="/" component={LoginForm}></Route> <Route path="/markers" component={Markers}></Route> <Route path="/contact" component={Contact}></Route> </div> </Provider > </BrowserRouter>
谢谢你的帮助.
创建一个状态变量redirectToNewPage,当true为重定向时.在回调集中,redirectToNewPage等于true.
class LoginForm extends React.Component { state = { redirectToNewPage: false } const submit=({email='',password=''})=>{ ... else{ //redirect to new page this.setState({ redirectToNewPage: true }) } } render() { // The part that makes the redirect happen if (this.state.redirectToNewPage) { return ( <Redirect to="/pageAfterSubmit"/> ) } return ( ... ) } }