将 React 状态变量插入 URL 时出现问题

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

我在更新 React 应用程序中的 URL 时遇到问题。我的 URL 如下所示:http://localhost:8080/${id}。我想从我的状态变量动态插入 id 的值,该变量在同一文件的顶部定义为: const [id, setId] = useState(null); 但是,当我调试问题时,似乎 ${id} 返回的值被解释为正则表达式,而不是 id 的实际值。

这是我所拥有的: const [id, setId] = useState(null); // 设置 id 的一些代码 const url =

http://localhost:8080/${id}
; 控制台.log(url); // 这将返回正则表达式而不是 id 值

javascript reactjs react-native url react-hooks
1个回答
0
投票

由于未共享完整代码,我只能看到您在创建 URL 字符串时缺少反引号(参见文档)。

import { useEffect, useState } from "react";

const App = () => {
  const [id, setId] = useState(null);

  useEffect(() => {
    /* some logic... */
    setId("myId");
    const url = `http://localhost:8080/${id}`; // <== THIS 
    console.log(url);
  }, [id]);


  return (
    /* some html/jsx... */
  );

}

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.