Reactjs React路由器访问路由组件中的路由属性

Reactjs React路由器访问路由组件中的路由属性,reactjs,react-router,react-router-dom,Reactjs,React Router,React Router Dom,我正在使用React router v4渲染路由。我有一个简单的路由组件,它路由到项目列表和一个编辑现有/添加新项目。这是一个使用引导构建的简单选项卡组件。我想根据路线是否具有id属性,将选项卡组件的标题更改为添加新的或编辑现有的 理想情况下,我希望避免创建额外的组件,因为这样做不会增强代码的可读性 public render() { const { match, location } = this.props; const customers = cx({ active: !

我正在使用React router v4渲染路由。我有一个简单的路由组件,它路由到项目列表和一个编辑现有/添加新项目。这是一个使用引导构建的简单选项卡组件。我想根据路线是否具有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>;
}
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={/*以某种方式读取匹配参数以获取id*/};
返回
  • items
  • {/*我想根据当前路由是否具有id参数来表示新建项或编辑现有项*/}
; }

有各种各样的破解方法——其中最好的方法似乎是读取
location.pathname
属性,并使用它来确定它是编辑还是添加新内容——这就足够了,但我忍不住觉得我在中遗漏了一些东西。您可以尝试为编辑和添加分离路由,但可以使用带有类型属性的相同组件

示例

    <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>

()}>
()}>
()}>

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

在您的
项目
组件中,您将通过路由路径的对象获得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
}