从组件中的axios获得响应

时间:2018-03-05 16:40:44

标签: javascript node.js reactjs redux axios

我有一个组件,它循环遍历帖子列表,并为每个帖子发出get请求,以查看当前用户是否喜欢这篇文章。我正在返回数据,但问题是我在渲染renderContent()中的内容之前似乎无法等待请求的响应。我收到错误“await是一个保留关键字”。我该怎么写这个?谢谢你的帮助!

import React, {Component} from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../../actions';
import axios from 'axios';

class PostsSection extends Component {

  constructor(props){
    super(props);

    this.heartClick = this.heartClick.bind(this);
  }

  componentDidMount() {
    this.props.fetchPosts();
  }

  heartClick(postId){
    const userId = this.props.auth._id;
    const values = {postId, userId};
    this.props.likePost(values);
  }

  didLikePost(userId, postId){
    let didLike = false;
    try {
      const res = axios.get("/api/did_user_like", {
        params: {
          postId: postId,
          userId: userId
        }
      })
      .then(function(result){
        console.log(result.data);
        if(result.data == null){
          didLike = false;
        } else {
          didLike = true;
        }
      });
    } catch(err){
    }
    return didLike;
  }

  async renderContent(){

    if(this.props.posts){
      return this.props.posts.map(entry => {
        let ftImgUrl = 'https:' + entry.fields.featuredImage.fields.file.url;
        let postId = entry.sys.id;
        let title = entry.fields.title;
        let authorName = entry.fields.authorName;
        const userId = this.props.auth._id;

        let didLike = await this.didLikePost(userId, postId);
        let heartActive = didLike ? "active" : "";
        return (
          <div className="w-col w-col-4 post-container" key={postId}>
            <div className="img-container"></div>
            <img src={ftImgUrl} className="featured-ad thumb" />
            <div className="extras">
              <div className="left">
                <a>{ authorName }</a>
              </div>
              <div className="right">
                <div className={"heart " + heartActive} onClick={() => this.heartClick(postId)}></div>
              </div>
            </div>
          </div>
        )
      });
    }
  }

  render(){
    const {posts} = this.props;
    return (
      <div className="section">
        <div className="w-container">
          <div className="category-row w-row">
            { this.renderContent() }
          </div>
        </div>
      </div>
    )
  }
}


function mapStateToProps(state){
  return {
   auth: state.auth,
   posts: state.posts
  };
}

function mapDispatchToProps(dispatch){
  return bindActionCreators(actions, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(PostsSection);

1 个答案:

答案 0 :(得分:1)

您的问题出在此功能中。

async renderContent(){

    if(this.props.posts){
      return this.props.posts.map(entry => {
        let ftImgUrl = 'https:' + entry.fields.featuredImage.fields.file.url;
        let postId = entry.sys.id;
        let title = entry.fields.title;
        let authorName = entry.fields.authorName;
        const userId = this.props.auth._id;

        let didLike = await this.didLikePost(userId, postId);
        let heartActive = didLike ? "active" : "";
        return (
          <div className="w-col w-col-4 post-container" key={postId}>
            <div className="img-container"></div>
            <img src={ftImgUrl} className="featured-ad thumb" />
            <div className="extras">
              <div className="left">
                <a>{ authorName }</a>
              </div>
              <div className="right">
                <div className={"heart " + heartActive} onClick={() => this.heartClick(postId)}></div>
              </div>
            </div>
          </div>
        )
      });
    }
  }

如果您想使用await,使用它的功能必须标有async。现在即使您的async方法之前有renderContent,您实际上在await的回调中使用了map。您需要的是使用async标记您的地图回调。

看起来像这样。

async renderContent(){

    if(this.props.posts){
      return this.props.posts.map(async entry => {
        let ftImgUrl = 'https:' + entry.fields.featuredImage.fields.file.url;
        let postId = entry.sys.id;
        let title = entry.fields.title;
        let authorName = entry.fields.authorName;
        const userId = this.props.auth._id;

        let didLike = await this.didLikePost(userId, postId);
        let heartActive = didLike ? "active" : "";
        return (
          <div className="w-col w-col-4 post-container" key={postId}>
            <div className="img-container"></div>
            <img src={ftImgUrl} className="featured-ad thumb" />
            <div className="extras">
              <div className="left">
                <a>{ authorName }</a>
              </div>
              <div className="right">
                <div className={"heart " + heartActive} onClick={() => this.heartClick(postId)}></div>
              </div>
            </div>
          </div>
        )
      });
    }
  }