【发布时间】:2018-11-13 04:11:35
【问题描述】:
我的假设是我尝试从闭包中访问状态。 这在某种程度上不起作用:
当前代码:
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 按钮的输出命名并链接到各自的城市。
实际结果
TypeError: that.state.courses 未定义
【问题讨论】:
标签: reactjs closures javascript-objects