React Router List and Detail Route at the same time

ぃ、小莉子 提交于 2019-12-23 12:14:41

问题


I have an issue with react router 4. And I'm not sure if its solvable:

This is my application layout:

Which basically works. But the problem is that whenever I hit /items/:id/ via the link on the left side it also matches /items. Which causes the link list in the sidebar to rerender. The solution would be to nest the routes. But this is not possible due to the interface/DOM. The left sidebar needs be independent of the item detail. And I need to split those up like:

<div>
  <div className={styles.sidebar}>
    <HeaderContainer />
    <Switch location={location}>
      <Route exact path="/" component={Homepage} />
      <Route path="/items" component={Items} />
    </Switch>
  </div>
  <div className={styles.content}>
    <Route path="/items/:id" component={ItemDetail} />
  </div>
</div>

Thanks a lot for your help in advance!


回答1:


I had a similar layout and I used something like this

//App.jsx
<Router path="/" component={Page}>

//Page.jsx
<Layout>
  <MasterView>
  <DetailView>
</Layout>

//MasterView.jsx
componentDidMount() {
  const { dispatch } = this.props
  const data = await api.getData();
  dispatch(updateDetail(data));
}
connect()(MasterView)

// DetailView.jsx
import { connect } from 'react-redux';

render() {
  return <ul>{this.props.list.map((item) => <li>{item}</li>)}</ul>;
}

// map the props you need to redux state
const mapStateToProps = (state) => ({ list: state.data.list });
connect(mapStateToProps)(DetailView)


来源:https://stackoverflow.com/questions/51684048/react-router-list-and-detail-route-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!