代码之家  ›  专栏  ›  技术社区  ›  stone rock

如何使用React Router V4(侧栏)创建多个路由?

  •  0
  • stone rock  · 技术社区  · 7 年前

    我有 JSON data 板球队。cricket应用程序基本上是crud web应用程序,我们可以在其中创建新团队或删除现有团队。我想 map 每一个 sidebar routes 检查此项例如: https://reacttraining.com/react-router/web/example/sidebar 如果我单击某个特定的团队,则显示每个团队的数据。

    我已经浏览了react router文档,但是路由是硬编码的,但是如果我在侧栏中有板球队的动态列表,我如何在单击特定队时显示特定队的数据(参见屏幕截图)。

    文档中的路由是:

    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>
      }
    ];
    

    截图:

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   Vishal    7 年前

    在路由文件中,可以指定如下路由:

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

    然后在teamdetails组件中,您可以访问teamid,如下所示:

    this.props.match.params.id
    

    要在道具上配上火柴 withRouter .

    您可以使用路由器,如下所示:

    import { withRouter } from 'react-router';
    
    class TeamDetails extends React.Component {
        .....
        .....
    }
    
    export default withRouter(TeamDetails);
    

    更新OP的评论:

    在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));
    

    当您的teamdetails组件加载时,您将调用一个名为getteam的操作,该操作将inturn调用api。在减速器中,你将设置一个叫做team的状态。该状态(团队)将通过connect helper作为组件中的道具提供给您。