【问题标题】:componentDidMount returns empty object object axioscomponentDidMount 返回空对象对象 axios
【发布时间】:2018-02-01 09:52:11
【问题描述】:

我正在尝试获取一个 json 并将其包含在我的状态中。

奇怪的是,当我在componentDidMount 内使用axios 启动我的ajax 请求并且我console.log 在渲染方法内更新状态时,它返回一个空对象,然后状态更新。

Don't mind the "undefined"

我只想删除这个空对象。 我该怎么办?

代码如下:

 componentDidMount() {
    axios({
        method: 'get',
        baseURL: '/url',
        headers: {
            "foo": "bar",
            "key": "tata"
        },
        timeout: 3000,
        responseType: 'json'
    }).then(response => {
        const posts = response.data.blocks.map(post => {
            if (typeof post.description !== 'undefined' && typeof post.description !== '') {
                return post;
            } else {
                return;
            }
        });
        this.setState({posts});
    });
}

【问题讨论】:

    标签: ajax reactjs axios


    【解决方案1】:

    componentDidMount 在您的渲染方法之后调用,因此您最初在渲染方法中获得的是您在构造函数中设置的初始状态。由于 post 应该是一个数组,因此您可以在构造函数中将其初始化为一个空数组,例如

    constructor(props) {
        super(props);
        this.state ={
          posts: []
        }
    }
    

    一旦您在componentDidMount 中的请求完成,就会设置状态帖子,组件将重新渲染,因此您将第二次看到正确的数据。

    也检查这个答案

    Use componentWillMount or componentDidMount lifecycle functions for async request in React

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2021-02-03
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2014-09-29
      • 2015-02-11
      • 2020-12-21
      相关资源
      最近更新 更多