带有 React Router 的多参数

IT技术 javascript reactjs jsx
2021-05-12 11:48:55

我有两个组件,一个是AddList组件,第二个是DetailList组件我正在做的是每个li 中有一个 AddList 组件和按钮的列表每当用户单击任何按钮时,该特定LI 的相应 ID 和名称都会发送到DetailList组件,以便用户可以阅读有关该特定产品的更多信息。我正在使用 react 路由器,当我在路由中传递一个参数时,一切正常。我可以 console.log 尊重的 Id <Route exact path="/details/:id" component={DetailOffAdd} />但是当我在路由中传递第二个参数时,<Route exact path="/details/:id/:name" component={DetailOffAdd} />我的组件没有安装,也没有显示任何错误。它也不会对我在 DetailList 组件中打印的 id 和 name 进行控制台。

这是我的AddList

导出默认类 Addlist extends Component { constructor(props) { super(props) this.state = { posts : [] } }

passToDetailList(id,name) {
     this.props.history.push('/details/'+id+name)
}
    render() {
      const { posts } = this.state;
        return (
            <div className="container" id="listOfAdd">

            <ul className="addUl">
          {
            posts.map(post => {
              return (
              <li key={post.id}>
                <button onClick={() => this.passToDetailList(post.id, post.add_title)}>VIEW</button>

                </li> 
              );
            })}


           </ul>
         </div>

**And the DetailList Component**

    export default class DetailOffAdd extends Component {
    componentDidMount(){
        console.log(this.props.match.params.id) 
      }
    render() {
        return (
            <Fragment>
              Some code 
            </Fragment>
        )
    }
}
2个回答

您可以在路由器路径中使用单个 slug 来发送更多详细信息 -

<Route exact path="/details/:id" component={DetailOffAdd} />

let dataObj  = {
       id:1,
       name:"someProduct"
    }
let stringifyData = JSON.stringify(dataObj);

传递数据——

passToDetailList(id,name) {
  this.props.history.push('/details/'+stringifyData)
}

要获取详细信息文件中的数据 -

let data  = JSON.parse(this.props.match.params.id);
console.log(data) // here is your full data  

我认为您缺少一个“/”,请尝试将您的 passToDetailList 更改为:

this.props.history.push(`/details/${id}/${name}`)