【问题标题】:Await fetch returns 2 arrays and data can't be usedawait fetch 返回2个数组,数据不能用
【发布时间】:2021-12-19 22:55:23
【问题描述】:

我正在开发一个在后端使用 Express 并在前端做出反应的全栈项目。现在问题出在特定组件上。它应该从 /api/blogposts 获取数据库查询的结果。但后来就出错了。

这是我的代码:

import React from 'react';
import './Blogposts.css';
import SingleBpost from '../SingleBpost/SingleBpost.js';

class Blogposts extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            receivedPosts: []
        };
    }
    async getBpostsFromServer() {
            const response = await fetch("/api/blogposts");
            let myPosts = await response.json();
            this.setState({receivedPosts: myPosts});
        }
    componentDidMount() {
        this.getBpostsFromServer();
    }
    render() {
        console.log(this.state.receivedPosts);
        return(
            <div id="Blogposts">
            <SingleBpost title="Test" date="18/12/2021" author="Kepos Team" body="Hello, this is a test for the blogposts!" />
            </div>
        );
    }
}


export default Blogposts;

只有一个console.log:console.log(this.state.receivedPosts);但是控制台给了我两个结果:首先它打印一个我不认识的数组,然后它打印我需要的数组。 (这里是截图https://imgur.com/a/q40aVkq)。

但是当我尝试将 this.state.receivedPosts 中的数据输入到我的组件中时:

<SingleBpost title={this.state.receivedPosts[0].title} (etc etc) />

它不起作用(我的屏幕实际上变成了空白)。

有人知道我在这里做错了什么吗?感谢您的帮助!

【问题讨论】:

  • 第一个控制台日志输出是您在构造函数中的默认状态。获取数据后,它会使用获取的数据更新状态。
  • 您需要在访问之前检查收到的帖子是否存在

标签: javascript node.js reactjs


【解决方案1】:

您可以使用&amp;&amp; 来保护您免受这种情况的影响

render() {
        return (
            this.state.receivedPosts && this.state.receivedPosts.length
            <div id="Blogposts">
            <SingleBpost title="Test" date="18/12/2021" author="Kepos Team" body="Hello, this is a test for the blogposts!" />
            </div>
        );
    }

或者通过三元运算符处理:

 render() {
            return (
                this.state.receivedPosts && this.state.receivedPosts.length ?
                <div id="Blogposts">
                <SingleBpost title="Test" date="18/12/2021" author="Kepos Team" body="Hello, this is a test for the blogposts!" />
                </div> : null
            );
        }

【讨论】:

  • 这仍然会以错误告终,因为Boolean([]) 只会导致 true,但您需要检查长度
猜你喜欢
  • 2021-04-11
  • 2021-02-17
  • 1970-01-01
  • 2019-12-11
  • 2020-07-14
  • 2021-05-06
  • 2017-09-09
  • 2014-04-24
  • 1970-01-01
相关资源
最近更新 更多