Error when getting state value: Uncaught TypeError: Cannot convert undefined or null to object at Function.keys

Error when getting state value: Uncaught TypeError: Cannot convert undefined or null to object at Function.keys

我是超级新手,很抱歉问了这么简单的问题。

我正在尝试使用来自在线 API 的 ChartJS 创建图表。

我的 js 脚本:

 constructor(props) {
    super(props);
    this.state = {
        daily_data: [],
        hourly_data: [],
        currency: this.props.currency,
        chartData: {}
    }
    this.getChartData = this.getChartData.bind(this);

}

getChartData() {

    this.setState({
        chartData: {
            datasets: [
                {
                    label: Object.keys(this.state.daily_data[this.state.currency]),
                    data: Object.values(this.state.daily_data[this.state.currency]),
                    fill: false,
                    borderColor: "rgba(255,255,255,0.1)",
                    backgroundColor: "rgba(0, 0, 0,0.2)",
                    pointBackgroundColor: "rgb(255,255,255)",
                }
            ]
        }
    })

}

 componentWillMount() {
    fetch("https://asia-northeast1-s3688090-cc2018.cloudfunctions.net/cool-api")
    .then(res=>res.json())
    .then(result => this.setState({
        daily_data: result,
    }))
    .catch(error => console.log("error" + error));
      }


render() {
    this.getChartData();
    return (
   ....
    )
 }

问题发生在:label: Object.keys(this.state.daily_data[this.state.currency])

Uncaught TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
at ViewDetails.getChartData (bundle.js:82729)
at ViewDetails.render (bundle.js:82783)
at bundle.js:55899
at measureLifeCyclePerf (bundle.js:55180)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (bundle.js:55898)
at ReactCompositeComponentWrapper._renderValidatedComponent (bundle.js:55925)
at ReactCompositeComponentWrapper.performInitialMount (bundle.js:55467)
at ReactCompositeComponentWrapper.mountComponent (bundle.js:55363)
at Object.mountComponent (bundle.js:8034)

提取 API 工作正常,因为在我的反应工具中它实际上显示状态 daily_data 具有所有 API 值:

当我阅读文档以及 Whosebug 上的一些类似问题时,指出 ReactJS 不会立即改变更新并可以调用回调来解决问题,我不确定这是否真的是问题所在。

谢谢。

考虑给您的 label 键一个初始值,也许是一个空数组。

  • 尝试使用异步等待
  • 并将componentWillMount()更改为componentDidMount()

    async componentDidlMount() { const response = await fetch("https://asia-northeast1-s3688090-cc2018.cloudfunctions.net/cool-api"); const json = await response.json(); this.setState({ daily_data: json }); }