0

我从一个看起来像这样的端点获取一个 json:

{"section":{"name":"name","subsections":[
 {"name":"one","snippets":[{"title":"title","body":"body"}]},
 {"name":"two","snippets":[{"title":"title","body":"body"}]}]
}}

这就是我获取数据的方式:

fetchData() {
  axios.get('/api/data')
  .then(response => {
    this.setState({
      section: response.data.section
    })
  })
  .catch(error => {
    console.log(error);
  });
}

componentDidMount() {
  this.fetchData();
}

但是当我打电话时,this.state.section.subsections[0]我收到以下错误:

Uncaught TypeError: Cannot read property '0' of undefined

我知道这subsections是一个数组,但是要从中获取元素。我得到一个错误。有谁知道我可能做错了什么?

编辑:

我想访问渲染方法中的状态。我可以访问this.state.section.name,我也可以this.state.section.subsections在控制台上打印。但是,每当我尝试使用访问元素时,this.state.section.subsections[0]都会出现错误。

4

2 回答 2

2

您可能正试图在数据可用之前访问它,

尝试这个 :

this.setState({
    section: response.data.section
},() => {
    console.log('After state set :' ,this.state.section.subsections[0]);
});

如果你得到了console.loghere,问题就像我上面解释的那样,如果没有,那么你需要console.log(this.state.section)检查输出


第一个解决方案:

从渲染中提供默认的空数组

render(){
   const subsections = this.state.section.subsections || [];
   return(...)
}

第二种解决方案:

提供来自 reducer 的默认空数组作为初始状态

于 2017-10-17T07:56:05.977 回答
1

Uncaught TypeError: Cannot read property '0' of undefined当您尝试从undefined变量中检索属性时发生。

本质上,控制台试图告诉你this.state.section.subsections == undefined,因此你不能调用undefined[0].

this.state.section.subsections您可能想在轮询变量之前检查是否存在。

IE。

if (this.state.section.subsections) {

  // Exists.
  console.log(this.state.section.subsections)

} else {

  // Undefined.
  console.log(this.state.section.subsections)

}
于 2017-10-17T08:07:00.690 回答