【问题标题】:React router accessing route properties in route component反应路由器访问路由组件中的路由属性
【发布时间】:2017-09-07 08:47:59
【问题描述】:

我正在使用 React 路由器 v4 来渲染路由。我有一个简单的路由组件,它路由到项目列表和编辑现有/添加新项目。这是一个使用引导程序构建的简单选项卡组件。我想将选项卡组件的标题更改为Add newEdit existing,具体取决于路由是否具有 id 属性。

理想情况下,我希望避免需要创建额外的组件,因为这不会增强代码的可读性。

public render() {
    const { match, location } = this.props;

    const customers = cx({ active: !location.pathname.includes("AddEdit") });
    const editItem = cx({ active: location.pathname.includes("AddEdit") });

    const hasIdParam = {/* Some way to read match params to get the id */};

    return <div className='nav-component-container'>
        <nav>
            <ul>
                <li role="presentation" className={items}><NavLink to={`${match.url}/All`} activeClassName='active'>Items</NavLink></li>
                <li role="presentation" className={editItem}>
                    <NavLink to={`${match.url}/AddEdit`} activeClassName='active'>
                        {/* I'd like this to say either new item or edit existing based on whether the current route has an id parameter or not */}
                    </NavLink>
                </li>
            </ul>
        </nav>
        <Switch>
            <Route path={`${match.url}/All`} component={Customers} {...this.props}></Route>
            <Route path={`${match.url}/AddEdit/:id?`} component={Item}></Route>
        </Switch>
    </div>;
}

有各种 hack - 其中最好的似乎是阅读 location.pathname 属性并使用它来确定它是编辑还是添加新的 - 这已经足够了,但我不禁觉得我错过了一些东西在

【问题讨论】:

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


    【解决方案1】:

    在您的Item 组件中,您将通过路由路径的match 对象获得url 参数,即id

    var strId = props.match.params.id //ecma5
    let strId = this.props.match.params.id //ecma6
    

    基于strId,您可以更改标签标签。

    if(strId){
       //use edit lable
    }else{
      //add label
    }
    

    【讨论】:

      【解决方案2】:

      您可以尝试分离路由以进行编辑和添加,但可以使用带有 type 属性的相同组件。

      示例

          <Switch>
              <Route path={`${match.url}/All`} component={Customers} {...this.props}></Route>
              <Route path={`${match.url}/Details/:id?`} component={()=>(<Item type="detail" />)}></Route>
              <Route path={`${match.url}/Edit/:id?`} component={()=>(<Item type="edit" />)}></Route>
              <Route path={`${match.url}/Add/:id?`} component={()=>(<Item type="add" />)}></Route>
          </Switch>
      

      然后在您的Item 组件上,您可以检查this.props.type 并相应地渲染它。

      【讨论】:

        猜你喜欢
        • 2017-11-08
        • 1970-01-01
        • 2017-12-06
        • 2018-06-07
        • 1970-01-01
        • 2022-10-23
        • 2020-01-01
        • 2019-02-18
        • 1970-01-01
        相关资源
        最近更新 更多