【问题标题】:How do I pass Redux props to a separate component in a different Route with React Router v4?如何使用 React Router v4 将 Redux 道具传递给不同路由中的单独组件?
【发布时间】:2017-11-06 13:28:03
【问题描述】:

我正在使用 react、react router v4 和 redux 创建一个实时聊天应用程序。问题在于,您可能知道,react router v4 改变了很多东西,嵌套路由对我不起作用。

所以我有这个带有嵌套路由的代码不起作用

<Route path='/' component={App}>
    <Route path="/user" component={AddUser}/>
</Route>

它给了我这个错误Warning: You should not use &lt;Route component&gt; and &lt;Route children&gt; in the same route; &lt;Route children&gt; will be ignored

其中component={App},第一个&lt;Route path='/' 是一个redux 连接:

const App = connect(mapStateToProps, mapDispatchToProps)(Header) 

所以我的组件App 拥有我需要的所有props。一切正常,除了我需要将这些道具从App 传递给嵌套路由组件AddUser

如何将 redux props 传递给不同 Route 中的单独组件?

【问题讨论】:

标签: javascript reactjs react-router react-redux


【解决方案1】:

我通过阅读这篇博文找到了解决方案:https://medium.com/@5XvYrLT7/react-server-side-rendering-with-react-router-3-x-74cf87919b3

使用 react-router v4,你不再这样做了,不要嵌套:

<Route component={App}>
    <Route component={Index} />
    <Route component={About} />
</Route>

你现在就这样做。应用按原样嵌入您的路线:

<App>
    <Switch>
        <Route exact path="/" component={Index} />
        <Route path="/about" component={About} />
    </Switch>
</App>

【讨论】:

    【解决方案2】:

    当我们需要嵌套路由时,使用 react-router v4,我们不会嵌套路由。相反,我们将它们放在嵌套组件中。你可以在这里阅读更多内容:Nested routes with react router v4

    在您的情况下,您可以将“/user”路由放在 App 组件中,然后使用 render 而不是 component。因此,您可以像往常一样将您的 App 道具传递给 AddUser。

    <Route path='/' component={App}/>
    

    App.js

    class App extends Component{
      //...
      render(){
        return(
          //....
          <Route path="/user"
            render={() => <AddUser myProp={this.props.myAppProp}/>}/>
          //....
        )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-17
      • 2019-06-08
      • 2021-12-21
      • 2018-05-19
      • 1970-01-01
      相关资源
      最近更新 更多