【问题标题】:dollar sign symbol is not working in React美元符号在 React 中不起作用
【发布时间】:2022-12-02 22:30:05
【问题描述】:

我正在使用 React 构建一个 CRUD 应用程序。对于我想要编辑特定产品(点击的产品)的产品编辑页面,我需要获取产品的 ID。我在代码中使用了美元符号,但它没有变蓝(它不起作用)。我需要 URL 来更改单击时显示其 id 的特定产品。怎么做?我究竟做错了什么?

`

<Link className='btn btn-primary m-2'><i className="fa fa-eye" aria-hidden="true"></i></ Link>
          <Link className='btn btn-otline-primary m-2' to={"/product/edit/${product.id}"}>Edit</Link>
          <Link className='btn btn-danger m-2'>Delete</Link>

`

const onSubmit = async e => {
  e.preventDefault();
  await axios.put('http://localhost:3001/products/${id}', product);
  navigate.push("/");
  };

``

我以为当我单击“编辑”按钮时,我可以看到特定产品的“编辑”页面,但它显示如下:http://localhost:3000/product/edit/$%7Bproduct.id%7D。编辑部分后不是 id。

【问题讨论】:

  • 您需要使用反引号 (`) 才能使用 template literal。常规引号("')只是创建一个字符串。
  • 现在我想起来了;谢谢!

标签: reactjs crud dollar-sign


【解决方案1】:

应该是``不是''

 await axios.put(`http://localhost:3001/products/${id}`, product);

【讨论】:

    【解决方案2】:

    模板文字是使用 ` 符号创建的,这有效:

    let x = "def"
    console.log(`abc${x}`);
    // Prints: "abcdef"
    

    但是普通的字符串不会:

    let x = "def"
    console.log("abc${x}");
    // Prints: "abc${x}"
    

    请参阅MDN Reference 以了解有关模板字符串如何工作的更多信息。

    【讨论】:

      猜你喜欢
      • 2013-01-11
      • 2012-08-29
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 2022-06-20
      • 1970-01-01
      相关资源
      最近更新 更多