【问题标题】:How to make this dynamic URL request to an API?如何向 API 发出此动态 URL 请求?
【发布时间】:2021-11-20 21:44:10
【问题描述】:

我正在尝试调用一个 API,它的 URL 需要根据用户想要查找的内容进行更改。 它是 SUPERHERO API,当用户搜索超级英雄时,页面发送请求的 URL 需要修改。我在 React 中使用 Axios。 所以,这就是我想要做的。

function App() {
const [hero, setHero] = useState("");

useEffect(() => {
axios.get(`https://cors-anywhere.herokuapp.com/https://superheroapi.com/api/apikey/search/${hero}`)
.then((response)=>{
    console.log(response.data)
  }).catch((error)=>{
    alert("not found")
  })
}, [hero])

 return (
    <div className="App">
       <div className="input-container">
         <input id="heroName" type="text" placeholder="search hero"/>
         <button type="submit" onClick={setHero(document.getElementById("heroName").innerText)}>search</button>
       </div>
      </div>
)}

export default App;

我得到的错误是 TypeError: Cannot read properties of null (reading 'innerText')。那是代码的一部分,我实际上并不知道自己在做什么,哈哈。抱歉,我是个菜鸟。

【问题讨论】:

  • 在 React 应用程序中,您不应该从 DOM 中抓取数据。 (无论如何,它不会是innerText——它会是value。)您的输入值应该处于状态,并且您会引用它。我目前没有更完整的解决方案,但我会从那里开始。

标签: reactjs api url axios request


【解决方案1】:

这看起来像是 useRef 的一个很好的“用例”:

import { useRef } from 'react'

function App() => {

const textInput = useRef(null)

function handleSubmit() {
// do stuff with the input here, where the ref value is {ref}.current.value...
const hero = textInput.current.value
axios.get(`https://cors-anywhere.herokuapp.com/https://superheroapi.com/api/apikey/search/${hero}`)
.then((response)=>{
    console.log(response.data)
  }).catch((error)=>{
    alert("not found")
  })
}

return (
    <div>
      <input
        type="text"
        ref={textInput} />
      <input
        type="button"
        value="Type the hero name hero"
        onClick={handleSubmit}
      />
    </div>);
)}

https://reactjs.org/docs/refs-and-the-dom.html

【讨论】:

    猜你喜欢
    • 2020-01-20
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 2013-07-11
    相关资源
    最近更新 更多