簡體   English   中英

如何在 React 中將 URL 參數添加到當前 URL 中?

[英]How to add a URL parameter to current URL in React?

我目前在 Post 組件中,並通過 Fetch Api 從“/home”路徑獲取數據。

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

更改對 json 數據的響應,並將 state 設置為 data.port_symbols。 但是現在我想用state中的數據作為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]}可以轉入state中存儲的值,但是${port[0]}/${port[1]}不能轉入將值輸入到 URL 中,URL 只顯示$%7Bport[0]/$%7Bport[1]%7D%7D

任何人都可以幫助找出問題所在並幫助解決它嗎? 謝謝你。

我認為您只需要將其設為模板字符串:

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

反引號“`”將允許您使用${variable}語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM