简体   繁体   English

React 从组件中的 axios 获取响应

[英]React getting response from axios in component

I have a component which is looping through a list of posts and making a get request for each to see if the current user liked this post.我有一个组件,它循环浏览帖子列表并为每个帖子发出一个 get 请求,以查看当前用户是否喜欢这篇帖子。 I'm returning the data but the problem is I can't seem to wait for the response from the request before rendering content in renderContent().我正在返回数据,但问题是在 renderContent() 中呈现内容之前,我似乎无法等待来自请求的响应。 I'm getting an error "await is a reserved keyword".我收到一个错误“await 是一个保留关键字”。 How should I be writing this?我该怎么写这个? Thanks for your help!谢谢你的帮助!

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

Your issue is in this function.您的问题出在此功能中。

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

When you want to use await the function using it must be marked with async .当你想使用await ,使用它的函数必须用async标记。 Now even though you have async before your renderContent method, you are actually using await in the callback of map .现在,即使您在renderContent方法之前有async ,您实际上是在map的回调中使用await What you need to is mark your map callback with async as well.您需要使用async标记您的地图回调。

It would look like this.它看起来像这样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 Axios 的响应数据存储到 React Functional Component 中的变量? - How to store response data from Axios to a variable in React Functional Component? React 组件不呈现 Axios 请求的响应 - React component not rendering response of Axios request 将 axios 响应传递给反应中的子组件 - passing axios response to child component in react React.js + Axios 在 const 组件中从 Http 响应中分配数据 - React.js + Axios Assign data from Http response in const Component 从axios响应中反应设置状态 - React setting state from an axios response 响应未从 axios 呈现响应获取请求 - Response not rendering from axios get request in react 如何在反应中设置 axios 的响应状态 - How to set state of response from axios in react 从使用 React 的会话存储(用户身份验证)上传递的 axios 获取响应只能正常工作一次,再也不会 - Getting the response from axios passed on Session storage (user authtoke) with React works fine only once and never again 从 POST 请求获取响应数据后 React JS &amp; Axios Render - React JS & Axios Render after getting response data from POST request 无法显示React中的Axios获取方法响应,无法在我的博客应用程序中以数组的形式从Firebase获取数据 - Axios get method response in React cannot be displayed getting data from firebase as an array in my blog application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM