【问题标题】:React + Fetch+ Json. TypeError: Cannot read property of undefinedReact + Fetch + Json。 TypeError:无法读取未定义的属性
【发布时间】:2017-06-21 08:16:08
【问题描述】:

当我使用 SuperAgent 时,我没有遇到这个问题,但我决定使用 Window.fetch polifyl 并遇到了这个问题。我看到所有数据都已加载,但仍然显示错误。 请您帮我识别此错误:

在 render() 中,我根据获得的列表生成组件列表:

    render() {

    if (this.state.data.list) {
        console.log("render: " + this.state.data.list);
        var counter = 0;
        const list = this.state.data.list.map((item) => {
....

【问题讨论】:

  • 你没有关闭第一个 thenable 调用。
  • 我想是这样的:获得响应后,将此响应发送给下一个函数,并将该函数的结果发送给下一个函数,但我没有返回任何结果。这意味着我不会在没有函数链中函数返回值的情况下传输任何数据......

标签: json reactjs promise fetch typeerror


【解决方案1】:

屏幕截图中的承诺处理程序不起作用:

.then((json) => console.log('parsed json: ', json))
.then((json) => { this.setState({ data: json }); })

“从解析这个promise中获取值并将其传递给console.log。然后,将console.log的返回值(即undefined)传递给this.setState。”

【讨论】:

  • 谢谢提示! fetch(url, { headers: { 'Accept': 'application/json', }, }).then((response) => response.json() .catch(err => { console.err('${err}' 发生了!); return {}; })) .then((json) => { console.log('parsed json: ', json); this.setState({ data: json }) }) .catch((err) => { console.log('fetch request failed: ', err) } )
【解决方案2】:
    fetch(url, {
        headers: {
            'Accept': 'application/json',
        },
    }).then((response) => response.json()
        .catch(err => {
            console.err(`'${err}' happened!`);
            return {};
        }))
        .then((json) => {
            console.log('parsed json: ', json);
            this.setState({ data: json })
        })
        .catch((err) => { console.log('fetch request failed: ', err) }
        )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2021-09-24
    • 2020-07-10
    • 2019-07-07
    • 2021-03-10
    • 2020-02-10
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多