首页 > 解决方案 > 如何在 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 未定义

标签: reactjsclosuresjavascript-objects

解决方案


正在从服务器获取课程,因此响应将在处理请求后出现。但是在初始渲染函数中没有调用 state 属性courses。所以你可以在构造函数中将它们设置为空。

constructor(props) {
 super(props);
 this.state={courses : {`what so ever is the data type`}}
}

并在渲染时检查是否this.state.courses不为空。


推荐阅读