无法使用带有React.js和Axios的地图循环遍历数组

时间:2019-08-09 11:45:17

标签: reactjs axios frontend

我正在从API中获取数据,我在console.log(this.state.reviews)中获取了所有数据,但是在映射循环完成之后我无法访问数据。

品牌数据可访问,唯一的问题是地图循环(评论数组)

我知道它与异步调用有关!我发现了这个Can't access values for Axios calls in map loop,有人知道如何使用下面的代码进行修改;-)

class App extends React.Component {

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

componentDidMount() {
    axios.get(`https://api.prime.com/businesses/reviews/${this.props.BrandId}`)
    .then((res) => {
        const brand = res.data;
        this.setState({
            // Reviews data
            reviews : brand.reviews.items,
            // Brand data
            logo   : brand.business.logo,
            name   : brand.business.name,
            voters : brand.business.voters,
            url    : brand.business.url
        });
    })
}
    render() {
    console.log(this.state.reviews);
    return (
            <div className="widget-wrapper">

                    <OwlCarousel className="reviews-container"
                        loop
                        nav
                        margin={12}
                        dots={false}
                        items={5}
                        autoplay={true}
                    >
                        {this.state.reviews.map((review) => {
                            <div key={review.id} className="review-item">
                                <a href={this.state.url + '/' + review.slug} target="_blank" rel="nofollow">
                                    <div className="review-heading">{review.subject}</div>
                                    <div className="review-content">{review.message}</div>
                                </a>
                            </div>
                        })}
                    </OwlCarousel>

            </div>
    )
}
}

1 个答案:

答案 0 :(得分:0)

我发现了您的问题,您需要等待诺言解决,为什么您的状态未设置为执行此操作,您可以像

那样使用async await
    import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
  }

  componentDidMount() {
    this.loadData();
  }
  loadData = async () => {
    const res = await axios.get("https://jsonplaceholder.typicode.com/posts");
    if (res) {
      const posts = res.data;
      this.setState({
        posts: [...posts]
      });
    }
  };
  renderPost = () => {
    return this.state.posts
      ? this.state.posts.map(data => (
          <div style={{ color: "black" }}>
            <h5>{data.title}</h5>
            <p>{data.body}</p>
          </div>
        ))
      : "loading...";
  };
  render() {
    console.log(this.state.posts);
    return <div> {this.renderPost()}</div>;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

完整的应用程序在这里签出:codesandbox