我正在重新路由我的应用程序。我有一个表单,我希望在表单成功提交后重定向用户。我把逻辑放在api成功之后。我的url发生了更改,但该url上要加载的组件没有加载。
import { browserHistory } from '../router/router';
...
export const storeRecord=(data)=>{
return function(dispatch, getState){
//console.log('state',getState());
const {authToken, userId} = getState().authReducer;
token= authToken;
data.userId = userId;
const url = 'investment/store';
apiCall(url, data, dispatch,'post').then((data)=>{
try{
if(data.status=== 200){
//let data = apiResponse.data
console.log('success',data);
browserHistory.push('/');
//dispatch(push('/'));
}
}
catch(error){
console.log('returnedError',error);
}
}, (error)=>{console.log(error)});
}
}
这也是我的路线:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';
...
export const browserHistory = createBrowserHistory();
const AppRouter=()=>{
return(<Router>
<LoaderModal />
<Switch>
<Route path="/" exact component={LandingPage} />
<PublicRouter path="/register" exact component={SignupPage} />
<PublicRouter path="/login" exact component={LoginPage} />
<PrivateRoute path="/investment/new" exact component={InvestmentForm} />
<Route component={NotFoundPage} />
</Switch>
</Router>)
}
export default AppRouter;
我使用react路由器dom进行重新路由,并使用历史记录进行浏览器重新路由。
您可以使用以下代码来代替在storeRecord组件中使用的dispatch(push('/'((。
window.location.assign('/'(;
您需要使用路由器模块用于动态路由的相同历史对象。
最简单的解决方案是不使用浏览器路由器,而是使用具有自定义历史的路由器
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';
...
export const browserHistory = createBrowserHistory();
const AppRouter=()=>{
return(<Router history={browserHistory}>
<LoaderModal />
<Switch>
<Route path="/" exact component={LandingPage} />
<PublicRouter path="/register" exact component={SignupPage} />
<PublicRouter path="/login" exact component={LoginPage} />
<PrivateRoute path="/investment/new" exact component={InvestmentForm} />
<Route component={NotFoundPage} />
</Switch>
</Router>)
}
export default AppRouter;
然后你的动作看起来像
import { browserHistory } from '../router/router';
...
export const storeRecord=(data)=>{
return function(dispatch, getState){
const {authToken, userId} = getState().authReducer;
token= authToken;
data.userId = userId;
const url = 'investment/store';
apiCall(url, data, dispatch,'post').then((data)=>{
try{
if(data.status=== 200){
browserHistory.push('/');
}
}
catch(error){
console.log('returnedError',error);
}
}, (error)=>{console.log(error)});
}
}