【问题标题】:Can't loop through array using map loop with react.js & axios无法使用带有 react.js 和 axios 的 map 循环遍历数组
【发布时间】:2019-08-09 11:45:17
【问题描述】:

我正在从 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>
    )
}
}

【问题讨论】:

  • 您需要在.map 箭头函数中使用return,或者将您的.map 箭头函数更改为使用(。因为您使用的是this.state.reviews.map((review) =&gt; {(带有大括号),所以返回并不像使用( 那样隐含。
  • @BrettDeWoody 我已经尝试过了,但我没用,我认为它与异步调用有关
  • 您是否遇到任何错误?
  • @BrettDeWoody 我没有收到错误,这和stackoverflow.com/questions/48969613/…是一样的

标签: reactjs axios frontend


【解决方案1】:

我发现你的问题你需要等待承诺解决为什么你的状态没有设置为这样做你可以使用async await like

    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

【讨论】:

  • 我没有收到错误,我只是无法循环数组评论,我可以在 console.log(this.state.reviews) 中看到数据,但我无法显示它
  • 您的代码返回错误 Uncaught ReferenceError: regeneratorRuntime is not defined (constructor(props) {)
  • @Elchy 检查沙箱的工作情况我不知道你在代码中做错了什么!
  • 我认为这是因为 babel-plugin-transform-runtime
  • 是的,你的代码有效 :),我不得不更改 @babel/plugin-transform-runtime 的版本。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
  • 2021-06-20
相关资源
最近更新 更多