【问题标题】:React - How redirect to another component after making an request?React - 发出请求后如何重定向到另一个组件?
【发布时间】:2018-01-13 18:43:39
【问题描述】:

我是新来的,正在寻找与钓鱼者 $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 >

【问题讨论】:

  • 你可以在这里找到一个非常完整的答案:stackoverflow.com/questions/42123261/…
  • 我确实看过答案。由于大多数建议的答案对于尝试进行“简单”重定向似乎有点过多,因此我尝试了建议的 ,但它不起作用。
  • answer 也使用 Browserrouter 而不是 Hashrouter,就像我必须使用的那样,否则我无法刷新页面而不会出现“无法获取 ...”错误,而答案又是使用哈希路由器而不是 BrowserRouter

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


【解决方案1】:

一个很好的方法是通过历史库(如果你还没有它,你可以这样做npm install history --saveReact-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 >

【讨论】:

  • 谢谢。你能解释一下 { some: stateifneeded }) - 我会在这里传递什么?
  • 如果您的组件(应用程序)的状态类似于“this.state = { loggedIn: true }”,那么您可以将其传递给被重定向到的组件,并在道具的形式。如果您不需要 {some:stateifneeded},我认为不需要该参数。例如,如果您有某种类型的登录/注销状态,您可以像 {logInfo: this.state.loggedIn} 一样传递它。
猜你喜欢
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 2012-07-28
  • 2015-08-29
  • 2021-01-06
  • 2019-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多