且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对象作为 React 子级无效(发现:[object Promise])

更新时间:2022-12-17 08:51:26

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

你需要这样做

componentDidMount() {this.renderPosts();}renderPosts = async() =>{尝试 {const res = await axios.get('/posts');常量帖子= res.data;//这将使用新数据重新渲染视图这个.setState({帖子:帖子});} 捕捉(错误){控制台日志(错误);}}使成为() {const posts = this.state.Posts?.map((post, i) => (<li key={i} className="list-group-item>>{post.text}</li>));返回 (
<ul className="list-group list-group-flush">{帖子}</ul></div>);}

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

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>
    );
  }

All I get is:

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.

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() will return a Promise not the actual data, and AFAIK Reactjs will not resolve Promises implicitly in render.

You need to do it like this

componentDidMount() {
  this.renderPosts();
}

renderPosts = async() => {
  try {
    const res = await axios.get('/posts');
    const posts = res.data;

    // this will re render the view with new data
    this.setState({
      Posts: posts
    });
  } catch (err) {
    console.log(err);
  }
}

render() {
  const posts = this.state.Posts?.map((post, i) => (
    <li key={i} className="list-group-item">{post.text}</li>
  ));

  return (
    <div>
      <ul className="list-group list-group-flush">
        {posts}
      </ul>
    </div>
  );
}

相关阅读

技术问答最新文章