【问题标题】:Error when getting state value: Uncaught TypeError: Cannot convert undefined or null to object at Function.keys获取状态值时出错:未捕获类型错误:无法在 Function.keys 将未定义或 null 转换为对象
【发布时间】:2018-09-30 10:35:51
【问题描述】:

我很陌生,很抱歉问了这么简单的问题。

我正在尝试使用来自在线 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)

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

由于我阅读了文档以及 StackOverflow 上的一些类似问题,表明 ReactJS 不会立即改变更新并且可以调用回调来解决问题,我不确定这是否真的是问题所在。

谢谢。

【问题讨论】:

    标签: reactjs api react-chartjs


    【解决方案1】:
    • 尝试使用异步等待
    • 并将 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 }); }

    【讨论】:

    • 如果您尝试在状态上使用虚拟货币,仍然会出错? currency: "AUD"
    • 是的,尝试了硬编码:Object.keys(this.state.daily_data["AUD"]) 仍然调用相同的错误。我认为问题出在我打电话给this.state.daily_data 的那一刻,它仍然为空。
    • console.log(this.state.daily_data) at getChartData() 返回数组长度 0。
    • 哦,在将 this.getChartData() 添加到异步 componentDidMount() 之后,它可以工作了!!!非常感谢。
    【解决方案2】:

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

    【讨论】:

    • 嗨,尝试对标签值进行硬编码,但显示相同的错误。在数据字段中。
    • 您还应该从渲染方法中删除您的getChartData() 方法。您可以改为在 componentDidUpdate() 中调用它,前提是 dailyData 状态发生变化。
    • 我认为是因为 setState() 还没有更新,但我已经调用了this.state.daily_data[this.state.currency]
    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 2021-12-17
    • 2021-09-01
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    相关资源
    最近更新 更多