我正在做一个API调用,它接受一个查询参数,我想将该参数作为state的值输入,但是我无法使用$ {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 | )
答案 0 :(得分:0)
它是在组件类之外定义的事实,这就是为什么您无法运行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>
)
}
}