对象作为React子对象无效(找到:[object Promise]) [英] Objects are not valid as a React child (found: [object Promise])

查看:1687
本文介绍了对象作为React子对象无效(找到:[object Promise])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过数组映射来呈现帖子列表。我之前已经多次这样做但是对于一些

I am trying to render a list of posts by mapping through an array. I've done this many times before but for some

renderPosts = async () => {
    try {
      let res = await axios.get('/posts');
      let posts = res.data;
      return  posts.map((post, i) => {
        return (
          <li key={i} className="list-group-item">{post.text}</li>
        );
      });
    } catch (err) {
      console.log(err);
    }
  }

  render () {
    return (
      <div>
        <ul className="list-group list-group-flush">
          {this.renderPosts()}
        </ul>
      </div>
    );
  }

我得到的是:


未捕获错误:对象作为React子对象无效(找到:[object Promise])。如果你想渲染一个子集合,请使用数组。

Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

我已经检查了从renderPosts返回的数据,它是一个具有正确值且没有承诺的数组。这里发生了什么?

I've checked the data returned from renderPosts and it is an array with the correct values and no promises. What's going on here?

推荐答案

this.renderPosts()将返回a Promise 不是实际数据,AFAIK Reactjs不会在 render 中隐式解析Promise。

this.renderPosts() will return a Promise not the actual data, and AFAIK Reactjs will not resolve Promises implicitly in render.

你需要这样做

componentDidMount() {
  this.renderPosts();
}

renderPosts = async() => {
  try {
    let res = await axios.get('/posts');
    let posts = res.data;
    // this will re render the view with new data
    this.setState({
      Posts: posts.map((post, i) => (
        <li key={i} className="list-group-item">{post.text}</li>
      ))
    });
  } catch (err) {
    console.log(err);
  }
}

render() {
  return (
    <div>
      <ul className="list-group list-group-flush">
        {this.state.Posts}
      </ul>
    </div>
  );
}

这篇关于对象作为React子对象无效(找到:[object Promise])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆