简体   繁体   English

对于具有不同参数的相同路由,React-router路由不会更改

[英]React-router route doesn't change for same route with different paramters

I just picked up react-router , and I'm sure I'm doing something wrong, just couldn't figure out what from the documentation and samples. 我刚刚拿起react-router ,我确定自己做错了,只是无法从文档和示例中弄清楚。

I have 3 links pointing to the same component. 我有3个指向相同组件的链接。 The difference is the 2 parameters passed in the URL: 区别在于URL中传递了2个参数:

 <Router>
    <div>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/chart/0/0">Chart</Link></li>
        <li><Link to="/chart/1/0">Chart with grid</Link></li>
        <li><Link to="/chart/1/1">Chart with grid and axis</Link></li>
        <li><Link to="/doesnotexist">This link does exist</Link></li>
      </ul>

      <hr/>

      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/chart/:grid/:axis" render={
          props => <Chart grid={props.match.params.grid === '1'} axis={props.match.params.axis === '1'} />
        }/>
        <Route component={NoMatch}/>
      </Switch>
    </div>
  </Router>

If I click one of the 3 chart links, I get the right chart rendered, with the right props passed. 如果单击3个图表链接之一,则会显示正确的图表,并传递正确的props If I click another chart link nothing changes. 如果单击另一个图表链接,则没有任何变化。 If I click one of the other links ("home" or "does not exist") and then click a chart, it displays properly. 如果我单击其他链接之一(“主页”或“不存在”),然后单击一个图表,它将正确显示。 Clearly routing does not happen if only the parameters change. 如果仅更改参数,显然不会发生路由。

How can I get routing to happen every time, or am I approaching this wrong? 我如何才能每次都进行路由选择,还是我要解决这个错误? Is there a better way to pass parameters/props to the same component? 是否有更好的方法将参数/属性传递给同一组件?

You can simplify above code, 您可以简化以上代码,

<Route path="/chart/:grid/:axis" component={Chart} />

You can easily access this grid / access props inside Chart component using 您可以使用以下控件轻松访问Chart组件中的此网格/访问道具

const { axis, grid } = this.props.params

If you want to update something inside the Chart eg load new data source component 如果您想更新图表内的内容,例如加载新的数据源组件

use componentWillReceiveProps function 使用componentWillReceiveProps函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM