Objects are not valid as a React child (found: [object Promise])

前端 未结 2 2038
生来不讨喜
生来不讨喜 2020-12-05 09:35

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 {
          


        
相关标签:
2条回答
  • 2020-12-05 10:20

    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 {
        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>
      );
    }
    
    0 讨论(0)
  • 2020-12-05 10:22

    I also received the same error message when creating an async functional component. Functional components should not be async.

    const HelloApp = async (props) =>  { //<<== removing async here fixed the issue
      return (
        <div>
          <h2>Hello World</h2>
        </div>
      )
    }
    ReactDOM.render(<HelloApp />, document.querySelector("#app"))
    

    jsfiddle

    0 讨论(0)
提交回复
热议问题