this.state属性被视为“未定义”

时间:2019-06-26 02:44:43

标签: javascript reactjs

我正在从后端到前端获取数据。在我调用之后 python from sklearn.ensemble import RandomForestRegressor random_forest = RandomForestRegressor(n_estimators=12) random_forest.fit(X_train, y_train) from sklearn.tree import export_graphviz estimator = random_forest.estimators_[5] export_graphviz( estimator, out_file="nyc_tree.dot", rounded=True, filled=True ) ,然后调用let data = response.json()。因此,我正在创建一个数组,其中包含原始对象的键/值对。然后,我设置组件const bartData = Object.entries(data)的状态为属性this.setState({allStations: bartData})。这就是问题所在-我想通过视觉确认我正在获取正确的数据并以自己想要的方式对其进行操作,因此我调用allStations: [],它为我提供了正确的内容,但是当我进一步{{ 1}},我收到一条指出

的错误
  

this.state.allStations [0]未定义

为什么? 另外,我知道我正在将一个数组放入一个数组中,这就是为什么让console.log(this.state.allStations[0])给我原始数组的内容感到惊讶的原因。 console.log(this.state.allStations)的图片 this.state.allStations

console.log(this.state.allStations[0][0]

2 个答案:

答案 0 :(得分:1)

console.log(this.state.allStations[0])之前的渲染功能中,您应该检查状态值。 渲染功能在从后端获取数据之前执行,我的建议是

if(this.state.allStations) && console.log(this.state.allStations[0])

答案 1 :(得分:0)

执行条件渲染以防止其在发送响应之前显示数组。

添加类似内容:

constructor(){
    super(props);
    this.state = {
       isLoading: true,
       allStations: []
    }
}

您需要使用React生命周期并将Fetch保留在内部:

componentWillMount(){
    fetch('/base-station-routes') // Already Async
    .then(res => res.json()) // Convert response to JSON
    .then(res => this.setState({ isLoading: false, allStations: res})) // you can call it bartData, but I like to stick with res
    .catch(err => { //.catch() handles errors
        console.error(err) 
    })
}

,然后在您的渲染器中:

render(){
    return( 
          <div>
              {this.state.isLoading ? <span>Still Loading</span> : // do a map here over your data}
          </div>
    )
}

这可以防止在响应出现之前对数据进行任何操作。