React - 在发出请求后如何重定向到另一个组件?

时间:2017-08-06 08:55:55

标签: javascript reactjs redirect react-router react-router-v4

我很反应并寻找相当于钓鱼者$ state.go的东西。我使用路由器4,并不适合我。我在网上看到的其他东西似乎不适用于路由器4.任何帮助都会很棒!感谢

class App extends React.Component{
  ...
  axis.post(/signup,{info})
    .then(function(){
     <Redirect if successful />
  })
}

 <HashRouter>
   <Route exact path='/' component={Home}/>
   <Route path='/login' component={Login}/>
   ...
 </HashRouter >

1 个答案:

答案 0 :(得分:1)

这样做的一个好方法是通过历史库(如果你还没有它,你可以做npm install history --save React-Routerv4也使用这个库。

以下是ReactRouterv4在其文档中也链接到的文档: https://github.com/ReactTraining/history

import createHistory from 'history/createBrowserHistory';

class App extends React.Component{
  ...
  axis.post(/signup,{info})
    .then(function(){
   const history = createHistory();
//listen for changes in current location

    const listen = history.listen((location, action) => {
      console.log(action, location.pathname, location.state);
    });
  //push the state as props to the route that will be redirected to
      history.push('/RouteToRedirectTo', { some: stateifneeded });

      //redirect to the route you want
      history.go('/RouteToRedirectTo');
  })
}

 <HashRouter>
   <Route exact path='/' component={Home}/>
   <Route path='/login' component={Login}/>
   ...
   </HashRouter >