我正在进行 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
}
}
我希望使用处于 state 的值进行 API 调用,我打算创建一个搜索表单,然后允许用户将值传递给 state,然后该值将用作 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 | )
它是在组件类之外定义的,这正是您无法运行 API 调用的原因。
您需要在组件内的事件处理程序中定义它,就像这样
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>
)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句