reactjs - Axios 不会在 Click 调用的函数中从 API 更新状态,但可以在 React 中的组件挂载上使用相同的函数
问题描述
我正在使用 Axios 在基本 React 组件中进行基本 API 拉取。当我的组件挂载时,我提取了一个随机 Chuck Norris 引用的 API,它运行良好。但是,当我尝试在名为 onClick 的相同函数中创建新的拉取和更新状态时,我收到一条错误消息,提示“未处理的拒绝 (TypeError):无法读取未定义的属性‘setState’。”
但是,当我 console.log 来自 API pull 的值时,它们给了我预期的结果,所以我不明白为什么我可以 console.log 一个值,获取一个字符串,然后让 React 告诉我这个字符串是未定义的。
我查看了几个 stackoverflow 线程,我看到的答案看起来与我当前的非工作解决方案相同。任何见解将不胜感激。
import React, {Component} from 'react'
import axios from 'axios'
class App extends Component {
state = {
quote: ''
}
componentDidMount(){
axios.get('https://api.chucknorris.io/jokes/random')
.then(res => {
console.log('response', res.data.value)
this.setState({
quote: res.data.value
})
})
}
getNewFact(){
axios.get('https://api.chucknorris.io/jokes/random')
.then(res => {
console.log('response', res.data.value)
this.setState({
quote: res.value
})
})
}
render () {
return(
<div>
<h1>Chuck Norris Facts</h1>
<p>{this.state.quote}</p>
<button onClick={this.getNewFact}>get new fact</button>
</div>
)
}
}
export default App
解决方案
您必须使用箭头函数而不是普通函数,因为那this
不是直接指向该类。所以而不是:
getNewFact(){
axios.get('https://api.chucknorris.io/jokes/random')
.then(res => {
console.log('response', res.data.value)
this.setState({
quote: res.value
})
})
}
将会:
getNewFact = () => {
axios.get('https://api.chucknorris.io/jokes/random')
.then(res => {
console.log('response', res.data.value)
this.setState({
quote: res.data.value // also fix this or nothing will show after clicking the button
})
})
}
推荐阅读
- python - 我在做什么错 - CSV 文件中的 b/跳行错误
- python-3.x - 如何为 AWS Athena 服务编写 Pytest
- tsql - SELECT INTO 多个变量
- shell - 如何在带有 $* 的 shell 中使用带空格的路径
- javascript - 如何使用特定于环境的 firebase 配置来初始化 firebase 应用程序?
- javascript - HTML 标签与 React 中的 React 组件性能
- spring - “一对多”/“多对多”属性值类型不应该是“?延伸'
- python - 使用 Anaconda(1.15.4 或 1.14.0)安装 Pycbc 时版本不匹配
- python - Python - 如何更改默认的 os.sep?
- c++ - 如何在 SDI 应用程序的视图中插入多个 FormView