简体   繁体   English

如何使用React Router v4(Sidebar)创建多个路由?

[英]How can I create multiple routes using React Router v4 (Sidebar)?

I have JSON data of cricket teams. 我有板球队的JSON data The cricket app is basically CRUD web app where we can create new teams or delete existing team. 板球应用基本上是CRUD Web应用,我们可以在其中创建新团队或删除现有团队。 I want to map each of the sidebar routes check this for example: https://reacttraining.com/react-router/web/example/sidebar and display data for each of the team if I click on a particular team. 我要map每个sidebar routes请检查以下示例: https : //reacttraining.com/react-router/web/example/sidebar ,如果单击特定团队,则显示每个团队的数据。

I have gone through the react router docs but the routes are hard coded but if I have dynamic list of cricket teams in sidebar how can I display data of a particular team onclicking particular team (See screenshot). 我已经阅读了React Router文档,但是路线是硬编码的,但是如果我在侧边栏中有板球队的动态列表,如何在单击特定团队时显示特定团队的数据(请参见屏幕截图)。

Routes in docs are: 文档中的路由为:

const routes = [
  {
    path: "/",
    exact: true,
    sidebar: () => <div>home!</div>,
    main: () => <h2>Home</h2>
  },
  {
    path: "/bubblegum",
    sidebar: () => <div>bubblegum!</div>,
    main: () => <h2>Bubblegum</h2>
  },
  {
    path: "/shoelaces",
    sidebar: () => <div>shoelaces!</div>,
    main: () => <h2>Shoelaces</h2>
  }
];

Screenshot: 截图:

在此处输入图片说明

In your routes file you can specify a route like this: 在您的路线文件中,您可以指定如下路线:

<Route path="/teams/:teamId component={TeamDetails} />

And then in TeamDetails Component, you can access the teamId like: 然后在TeamDetails组件中,您可以像这样访问teamId:

this.props.match.params.id

To have match in your props you have to use withRouter . 要使道具匹配,必须使用withRouter

You can use withRouter as follows: 您可以按如下方式使用withRouter:

import { withRouter } from 'react-router';

class TeamDetails extends React.Component {
    .....
    .....
}

export default withRouter(TeamDetails);

Update for OP's comment: OP的评论更新:

In your TeamDetails component: 在您的TeamDetails组件中:

import { withRouter } from 'react-router';
import { connect } from 'react-redux';

class TeamDetails extends Component {
  componentWillMount() {
    this.props.getTeam(this.props.match.params.id)
  }

  render() {
    console.log(this.props.team);
    return (......);
  }
}

const mapStateToProps = state => ({
  teams: state.teams.team,
});

const mapDispatchToProps = dispatch => ({
  getTeams: teamId => dispatch(actions.getTeams(teamId)),
});

export default connect(mapStateToProps, mapDispatchToProps)(withRouter(TeamDetails));

When your TeamDetails component loads you will call an action called getTeam which will inturn call api. 当您的TeamDetails组件加载时,您将调用一个名为getTeam的操作,该操作将依次调用api。 And in your reducer you will set a state called team. 并且在减速器中,您将设置一个称为团队的状态。 That state (team) will be available to you as a prop in your component via connect helper. 该状态(团队)将通过连接助手作为组件中的道具提供给您。

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

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