【问题标题】:React-router-dom: Render two components under one routereact-router-dom:在一个路由下渲染两个组件
【发布时间】:2017-10-24 14:23:26
【问题描述】:
<Provider store={store}>
    <BrowserRouter>
        <div>
            <Switch>
              <Route
                path="/test/:id"
                component={Question1} />
              <Route
                path="/test/:id"
                component={Question2} />
        </div>
    </BrowserRouter>
</Provider>

我需要从 ID 为 1 的 Question1 导航到 ID 为 2 的 question2。我可以毫无问题地从测试导航到 question1,但是当我想去提问时使用this.props.history.push('/test/2') URL更改,但我没有导航到 question2。

有什么想法吗?

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom


    【解决方案1】:

    您应该有一个 Question 组件来处理 id 并显示相应的问题。

    你可以使用Route的render方法来做同样的事情

      <Route
         path="/test/:id"
         render={(props)=>{
                 switch(props.match.params.id){
                      case "1": return <Question1/>;
                      case "2" : return <Question2/>;
                      default : return null;
                  }
         }}
      />
    

    编辑:注释后更正代码

    【讨论】:

    • 效果很好,只是在 props.match.params.id 中缺少参数
    【解决方案2】:

    这个问题是&lt;Switch&gt; 在这种情况下会匹配&lt;BrowserRouter/&gt; 下的第一个组件。如果它与第一个路径不匹配,它将尝试第二个。这就是Switch 的工作原理。所以在你的例子中path=/test/:id的路径模板实际上匹配/test/1和/test/2,并且Route总是呈现Question1而不是Question2。在此处查看文档 https://reacttraining.com/react-router/web/api/Switch.

    您可以做的一件快速的事情是,如果您知道自己只有两个 Questions,那么您可以这样做

              <Route exact
                path="/test/1"
                component={Question1}
              />
              <Route exact
                path="/test/2"
                component={Question2}
              />
    

    这将立即解决您的问题,但我不建议这样做,因为当您获得更多 Questions 时它会变得不合理。 @palsrealm 建议使用更好的设置。

    【讨论】:

      【解决方案3】:

      您可以通过一条路线完成此操作,并在您的组件中加载正确的问题:

      <Route path="/test/:id" component={Question} />
      
      // Question.js
      export default React.createClass({
        render() {
          return (
            <div>
              <h2>Question {this.props.params.id}</h2>
            </div>
          )
        }
      })
      

      文档:route-with-parameters

      【讨论】:

        猜你喜欢
        • 2019-04-12
        • 2019-12-23
        • 2019-03-13
        • 2019-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        • 2018-10-18
        相关资源
        最近更新 更多