javascript - 类型错误 : Cannot read property state of null

标签 javascript reactjs

我无法让数据脱离状态并在其上应用 map 功能。我不断得到

TypeError: Cannot read property 'financials' of null.

axios 获取以下对象,{symbol: "AAPL", financials: Array(4)},这就是我使用 this.state.financials.financials 的原因

class Fundamentals extends Component {
  state = {
    financials: null,
    headers: null
  };

  async componentDidMount() {
    console.log("componentDidMOunt");
    await axios
      .get("https://api.iextrading.com/1.0/stock/aapl/financials?period=annual")
      .then(res => {
        const financials = res.data;
        this.setState({ financials });
        console.log(financials);
      });

    console.log("componentDidMount finished setting the data for the table");
  }

  render() {
    // const headers = this.getHeaders1();
    return (
      <GridContainer>
        <GridItem xs={12} sm={12} md={12}>
          <Card>
            {this.state.financials.financials.map(items => items)} <-- i want to get the data out of state and later put it into a table. 
          </Card>
        </GridItem>
      </GridContainer>
    );
  }
}

最佳答案

组件第一次渲染时,this.state.financialsnull,因为您使用null 初始化它:

state = {
  financials: null,
  headers: null
};

这就是您收到该错误的原因。这是一个复制错误的简单示例:

var state = {
  financials: null,
};

state.financials.financials.map(() => {});

您需要检查您的渲染方法是否设置了该值,如果没有设置什么也不做:

render() {
  // const headers = this.getHeaders1();
  if (!this.state.financials) {
    return null; // or some message that the data is loading
  }

  return (
    <GridContainer>
      <GridItem xs={12} sm={12} md={12}>
        <Card>
          {this.state.financials.financials.map(items => items)} <-- i want to get the data out of state and later put it into a table. 
        </Card>
      </GridItem>
    </GridContainer>
  );
}

或者,您可以使用 {financials: []} 来初始化它:

state = {
  financials: {financials: []},
  headers: null
};

然后您在 render 中的现有代码应该“工作”(见下文)。


但仅此一项可能无法使您的组件正常工作。您还需要将 this.state.financials.financials 中的条目实际转换为 React 可以呈现的内容。这是一个提取日期的示例:

this.state.financials.financials.map(item => item.reportDate)

根据您的需要进行调整。

关于javascript - 类型错误 : Cannot read property state of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53531077/

相关文章:

javascript - React router v4 渲染元素内的组件

javascript - 为嵌套对象数组创建reducer

javascript - React Native 输入字段占位符在 iOS 中不起作用

reactjs - 可以从 Redux reducer 中发出 REST API 请求吗?

reactjs - 找不到模块 : Can't resolve 'bootstrap/dist/css/bootstrap.css' in 'C:\Users\test\counter-app\src'

javascript - jQuery 的多个 div 创建/销毁错误

reactjs - 在react-native中隐藏键盘

php - Jquery .post() 澄清

javascript - 如何在 Javascript 中正则表达式两个标记之间的字符串?

javascript - 当输入文本值更改时,我可以更改按钮文本吗?