如何将来自反应状态的值作为变量包含在 API 调用中作为查询参数的一部分

How to include a value from react state, as a variable, as part of a query parameter in an API call

我正在进行一个 API 调用,它接受一个查询参数,我想将该参数作为来自状态的值输入,但我无法将 ${this.state.mySearch} 用作查询参数的变量。

我曾尝试在 google 上搜索并在聊天室中寻求帮助,并在代码中乱搞了很多。


    state = {
        mySearch: 'apple'
      }
    ...

    ///This API call is defined outside of the main class component(not sure if that is ok)

    Index.getInitialProps = async function() {
      const res = await fetch(
        `https://newsapi.org/v2/everything?q=${this.state.mySearch}&apiKey=(privateApikey`
      )
      const data = await res.json()

      return {
        headlines: data
      }
    }

我希望使用状态中的值进行 API 调用,我打算创建一个搜索表单,然后允许用户将值传递给状态,然后用作API 调用中的变量。

我的错误信息是:

TypeError: Cannot read property 'mySearch' of undefined
Function._callee$
./pages/index.js:52
  49 |   }
  50 | }
  51 | 
> 52 | Index.getInitialProps = async function() {
  53 |   const res = await fetch(
  54 |     `https://newsapi.org/v2/everything?q=${this.state.mySearch}&apiKey=(myPrivateApiKey)`
  55 |   )

它是在您的 component-class 之外定义的,这正是您无法 运行 您的 API 调用的原因。

您需要在组件内的 event-handler 中定义它,类似于这样

class Example extends React.Component{
   state = {
      search: "",
      headlines: ""
   }

   handleOnChange = (event) => {
      this.setState({
        search: event.target.value
      })
   }

   handleOnSubmit = async (event) => {
       event.preventDefault()
       const res = await fetch(
       `https://newsapi.org/v2/everything?q=${this.state.search}&apiKey=(privateApikey`)
       const data = await res.json()

       this.setState({
          headlines: data
       })
   }

   render(){
     return(
     <form onSubmit={this.handleOnSubmit}>
         <input onChange={this.handleOnChange} value={this.state.search}/>
     </form>
    )
   }

}