reactjs - 如何在 React 中从闭包中访问状态
问题描述
我的假设是我尝试从闭包中访问状态。这在某种程度上不起作用:
当前代码:
export class CityChoice extends React.Component{
constructor(props) {
super(props);
this.state={}
}
componentDidMount(){
request
.get('http://XXX.XXX.XX.XX:3000/get_courses')
.set('Accept', 'application/json')
.then((res) => {
for (let key in res.body){
console.log(res.body[key].city)
}
this.setState({courses: res.body})
console.log("this.state.courses -> " + this.state.courses)
})
.catch(function(err) {
console.log(err)
});
}
render(){
var that = this
return (<div>
<h2>Wähle Deine Stadt</h2>
{
that.state.courses.body.city.map((city, index) => (
<p><Link to={{pathname: "/kurse", stadt: {city}}}><Button>{city}</Button></Link></p>
))}
}
</div>
)
}
}
预期结果
命名并链接到相应城市的 x 按钮的输出。
实际结果
类型错误:that.state.courses 未定义
解决方案
正在从服务器获取课程,因此响应将在处理请求后出现。但是在初始渲染函数中没有调用 state 属性courses
。所以你可以在构造函数中将它们设置为空。
constructor(props) {
super(props);
this.state={courses : {`what so ever is the data type`}}
}
并在渲染时检查是否this.state.courses
不为空。
推荐阅读
- python - Python 如何管理整数和浮点数的大小?
- python - 如何从fastapi中的另一个api调用一个api?
- r - read_excel 无法读取 xls(MS excel 5.0/95 工作簿),但可以通过另存为 .xlsx 读取
- javascript - 使用对象克隆方法和for循环将对象推入数组,对象仍然是相同的引用,并且在数组中是相同的
- javascript - React + Socket IO:访问第一条消息
- email - 允许对 SQL 数据库进行邮件传递
- image - 用于 JasperReport 中的图像的 Samba 共享
- java - Java - 停止执行并稍后恢复
- assembly - 如何在 sparc V8 处理器中设置 TBR?
- javascript - AdonisJs 图片上传