如何在React中将URL参数添加到当前URL?

问题描述 投票:0回答:1

我目前在Post组件中,并通过“ / home”路由通过Fetch Api获取数据。

 componentDidMount() {
   fetch('/home')
     .then(res => res.json())
     .then((data)=> {
       console.log(data.ports)
       this.setState({ports: data.ports})
     })
     .catch(error =>console.log(error))
 }

将响应更改为json数据,并将状态设置为data.port_symbols。但是现在我想使用状态数据作为URL参数,因此我尝试以下代码。

render() {   
return (
  <div>
    <h2>ports</h2> 
    <ul>
      {this.state.ports.map((port, index)=>          
         <li>
           <NavLink activeClassName='active-link' 
            to='/get_info/${port[0]}/${port[1]}'key={index}>
             {port[0]}/{port[1]}
           </NavLink>             
        </li>          
         )
      }   
    </ul> 

所以问题是,{port[0]}/{port[1]}可以转换为状态存储的值,但是${port[0]}/${port[1]}不能转换为URL的值,URL仅显示$%7Bport[0]/$%7Bport[1]%7D%7D

任何人都可以帮助找出问题所在并帮助解决问题吗?谢谢。

javascript reactjs fetch-api
1个回答
1
投票

我认为您只需要将此作为模板字符串即可:

   <NavLink activeClassName='active-link' 
    to=`/get_info/${port[0]}/${port[1]}` key={index}>
     {port[0]}/{port[1]}
   </NavLink> 

背号“`”将使您可以使用${variable}语法。

© www.soinside.com 2019 - 2024. All rights reserved.