渲染的输入在 React 中充当对象而不是字符串

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

呈现的输入被解释为单词“对象”,而不是在 React 中输入的文本。所以我有这个 API,我想在搜索时使用输入进行搜索,它得到的是文字“对象”,而不是我在写什么。

正在写入对象而不是我搜索的内容

1

在这里我搜索了输入,但对象再次被写入查询

2

import { useState } from "react";

function () {
  const [endpoint, setEndpoint] = useState("");

  function searchChange(e) {
    setEndpoint(e.target.value);
    console.log(endpoint);

    const options = {
      method: "GET",
      headers: {
        "X-RapidAPI-Key": "baef7285e6msh0aae02b3fd1dde5p1d01aajsne4c06de3d63f",
        "X-RapidAPI-Host": "spotify81.p.rapidapi.com",
      },
    };

    fetch(
      "https://spotify81.p.rapidapi.com/search?q=" +
        {endpoint} +
        "&type=albums&offset=0&limit=10&numberOfTopResults=5",
      options
    )
      .then((response) => response.json())
      .then((response) => console.log(response))
      .catch((err) => console.error(err));
  }
  return (
    <input
      className="input"
      value={endpoint}
      placeholder=" 🔍 Search"
      onChange={searchChange}
    />
  );
}
javascript reactjs api search searchqueryset
2个回答
0
投票

您的代码格式正确,但我注意到您构建 url 的方式可能不正确。

现在我看起来像你总是发送

q={endpoint}
作为字符串而不是变量。

尝试使用字符串插值将您的提取更改为此:

fetch(`https://spotify81.p.rapidapi.com/search?q=${endpoint}&type=albums&offset=0&limit=10&numberOfTopResults=5`,
options)

0
投票

在构建您的获取 URL 时,您添加

+{endpoint}+
这将导致一个带有
q
的字符串
[object Object]

"https://spotify81.p.rapidapi.com/search?q=[object Object]&type=albums&offset=0&limit=10&numberOfTopResults=5";

连接获取 URL 的正确方法如下,通过删除括号

{}

"https://spotify81.p.rapidapi.com/search?q=" +
  endpoint +
  "&type=albums&offset=0&limit=10&numberOfTopResults=5";

现在这将获取您的

endpoint
但它会落后一步(字符),因为 setState 是 sort of async 意味着您的
endpoint
函数内的
searchChange
值在下一次渲染之前不会更新。您可以直接使用 URL 中的
e.target.value
来解决此问题。

"https://spotify81.p.rapidapi.com/search?q=" +
  e.target.value +
  "&type=albums&offset=0&limit=10&numberOfTopResults=5";

或者当

useEffect
值改变时使用
endpoint

useEffect(() => {
  fetch(
    "https://spotify81.p.rapidapi.com/search?q=" +
      endpoint +
      "&type=albums&offset=0&limit=10&numberOfTopResults=5",
    options
  )
    .then((response) => response.json())
    .then((response) => console.log(response))
    .catch((err) => console.error(err));
}, [endpoint]);

这样您就可以在提取中使用

endpoint
值。

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