【问题标题】:Multiple Param with React Router使用 React 路由器的多个参数
【发布时间】:2020-09-10 22:46:08
【问题描述】:

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

这是我的AddList

导出默认类 Addlist 扩展组件 { 构造函数(道具){ 超级(道具) 这个.state = { 帖子:[] } }

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

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    您可以在路由器路径中使用单个 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  
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我仍然得到一个空白页,并且控制台中没有打印任何内容。但网址是这个http://localhost:3000/details/2/SECONDADD
      猜你喜欢
      • 2022-10-15
      • 2017-04-12
      • 1970-01-01
      • 2021-04-27
      • 2020-08-30
      • 2011-11-10
      • 2020-05-31
      • 1970-01-01
      • 2016-03-17
      相关资源
      最近更新 更多