Javascript React Router v4 重定向不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42875949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:29:23  来源:igfitidea点击:

React Router v4 Redirect not working

javascriptreactjsreact-routerreact-router-v4

提问by mdanishs

I have a route which redirects after checking a condition like this

我有一条在检查这样的条件后重定向的路线

<Route exact path="/" render={()=>(
Store.isFirstTime ? <Redirect to="intro" /> : <Home state={Store}/>)}/>

The url changes when the condition is true but the component is not mounted. The rest of the component code is as below.

当条件为真但未安装组件时,url 会更改。其余的组件代码如下。

render() {
    return (
      <div>
        ...
        <Route exact path="/" render={()=>(
          Store.isFirstTime ? <Redirect to="intro" /> : <Home state={Store} />         
        )} />
        <Route path="/intro" render={()=>(<IntroWizard state={Store.userInfo}/>)} />
        <Route path="/home" render={()=>(<Home state={Store}/>)} />
        <Route render={()=>(<h1>404 Not Found</h1>)} />
        <Footer />
      </div>
    );
  }

My App Component is contained with in the BrowserRouter like thi

我的应用程序组件包含在 BrowserRouter 中,如下所示

ReactDOM.render(<BrowserRouter>
    <App/>
</BrowserRouter>,
  document.getElementById('root')
);

when I hit the url directly in the browser like 'localhost:3000/intro' component is mounted successfully, but when it goes through the redirect it doesn't display the component. How do I fix it?

当我直接在浏览器中点击 url 时,如 'localhost:3000/intro' 组件已成功安装,但是当它通过重定向时,它不会显示该组件。我如何解决它?

Edit

编辑

So one detail was missing and I tried creating another project to reproduce the issue. My App component is a observer from mobx-react and it is exported as shown below

因此缺少一个细节,我尝试创建另一个项目来重现该问题。我的 App 组件是来自 mobx-react 的观察者,它的导出如下所示

let App = observer(class App { ... })
export default App

I have created this repo with a sample code to reproduce the issue you can use it https://github.com/mdanishs/mobxtest/

我用示例代码创建了这个 repo 来重现您可以使用它的问题 https://github.com/mdanishs/mobxtest/

So when Components are wrapped into mobx-react observer the redirect is not working else it works fine

因此,当组件被包装到 mobx-react 观察者中时,重定向不起作用,否则它工作正常

回答by neurozero

The asker posted an issueon GitHub, and got this apparently unpublished hidden guide(edit: now published) that helped me out too. I'm posting it here because I ran into the same problem and want others to avoid our pain.

提问者在 GitHub 上发布了一个问题,并得到了这个显然未发布的隐藏指南(编辑:现已发布),这也帮助了我。我在这里发布它是因为我遇到了同样的问题并希望其他人避免我们的痛苦。

The problem is that mobx-react and react-redux both supply their own shouldComponentUpdate()functions that only check for prop changes, but react-router sends state down through the context. When the location changes, it doesn't change any props, so it doesn't trigger an update.

问题是 mobx-react 和 react-redux 都提供了自己的shouldComponentUpdate()函数,只检查 prop 的变化,但是 react-router 通过上下文向下发送状态。当位置改变时,它不会改变任何道具,所以它不会触发更新。

The way around this is to pass the location down as a prop. The above guide lists several ways to do that, but the easiest is to just wrap the container with the withRouter()higher order component:

解决这个问题的方法是将位置作为道具向下传递。上面的指南列出了几种方法,但最简单的方法是用withRouter()高阶组件包装容器:

export default withRouter(observer(MyComponent))

or, for redux:

或者,对于 redux:

export default withRouter(connect(mapStateToProps)(MyComponent))

回答by nokieng

You should render only Redirectin your render method:

你应该只Redirect在你的渲染方法中渲染:

render() {
  return (<Redirect to="/" />);
}

but here is my favorite solution without using the Redirectcomponent

但这是我最喜欢的不使用Redirect组件的解决方案

  1. import import { withRouter } from 'react-router-dom';
  2. export default withRouter(MyComponent);
  3. Finally, in your action method, assume that handlingButtonClick
  1. 进口 import { withRouter } from 'react-router-dom';
  2. export default withRouter(MyComponent);
  3. 最后,在您的操作方法中,假设 handlingButtonClick
handlingButtonClick = () => {
  this.props.history.push("/") //doing redirect here.
}

回答by Kornelius

Be careful when composing the Router with other components like translation providers, theme providers, etc .. After some time I found that your App has to be strictly wrapped by the Router, like this:

将 Router 与其他组件(如翻译提供程序、主题提供程序等)组合时要小心。 一段时间后,我发现您的应用程序必须由路由器严格包装,如下所示:

<Provider store={store}>
  <ThemeProvider theme={theme}>
    <TranslationProvider
      namespaces={['Common', 'Rental']}
      translations={translations}
      defaultNS={'Common'}
    >
      <Router>
        <App />
      </Router>
    </TranslationProvider>
  </ThemeProvider>
</Provider>

Hope this helps somebody

希望这可以帮助某人

回答by Tyler McGinnis

You're missing a / in front of intro

你在介绍前面少了一个 /

<Route exact path="/" render={()=>(
  Store.isFirstTime ? <Redirect to="/intro" /> : <Home state={Store} />         
)} />

回答by Mahdy Aslamy

I have problem with <Redirct />and finally i found that <Redirect />have to not be inside <Switch></Switch>tags.

我有问题,<Redirct />最后我发现<Redirect />不必在<Switch></Switch>标签内。

回答by ali alizadeh

you can try this way like:

你可以试试这种方式:

first: import "withRouter" to component like this:

首先:像这样将“withRouter”导入到组件中:

import { withRouter } from "react-router-dom";

then at the end of your component export compoenent like this:

然后在您的组件导出组件的末尾,如下所示:

export default withRouter(VerifyCode);

and then you can add this code to your function:

然后您可以将此代码添加到您的函数中:

 verify(e) {
    // after sever get 200
    this.props.history.push('/me/');
}

good luck

祝你好运