【问题标题】:React - what are the steps to get data from api and render it?React - 从 api 获取数据并渲染它的步骤是什么?
【发布时间】:2020-07-18 09:35:46
【问题描述】:

我正在构建一个类似于 stackoverflow.com 的网站。我希望我的主页显示热门问题。为此,我有支持的示例问题。现在,我只想显示问题数组中的问题和标签。

代码在图片

我已经为此建立了 axios 连接:

const instance = axios.create({

baseURL: "https://2w2knta9ag.execute-api.ap-south-1.amazonaws.com/dev", });

instance.defaults.headers.post["Content-Type"] = "application/json";

为了连接它,我写了命令:instance.get("/questions)

现在,我如何只显示问题和标签??

编辑:

使用下面给出的代码,我的 js 文件现在变为:

import React from 'react';
import instance from '../../api';
class QuestionList extends React {

  componentDidMount() {
     instance
     .get("/questions")
     .then((res) => {
       this.setState({ data: res.data });
      });
  }

  render () {
    const { data } = this.state; 
    return <div>
      {
        data && data.map(d => {
          return <div>question: {d.question}, tags: {d.tags}</div>;
        })
      }
    </div>
  }
}   
export default QuestionList;

但是,这只是让我的网站处于加载状态,它会被挂起!!

【问题讨论】:

  • 这个问题太笼统了。请只询问您面临的具体问题。听起来你最好还是学习一下 React 和 Web 开发。
  • 是的,我是 React 新手
  • 与其创建一个复杂的网站,不如先学习基础知识。 React 有很多不同的概念,所以在会走路之前不要尝试跑步。

标签: reactjs axios render


【解决方案1】:

如果我理解正确,您只想获得一个带有标签和问题的数组。如果是这样,您可以为此使用Array.prototype.map

const questions = result.map(({ question, tags }) => ({ question, tags }))

【讨论】:

  • 如何在我的渲染函数中获取它?
  • 你知道如何将结果放入render方法吗?
  • 我认为如果你在向前跳跃之前学习一些 React 会更好
【解决方案2】:

首先,您导出 axios 实例,以便可以从其他组件中使用它。 现在您可以在componentDidMount 中发送 api 请求并使用数据更新组件的状态。 而在渲染函数中,您只需从状态和显示中获取值。

如果您是 react 新手,请学习 React Hooks 并知道componentDidMount 方法是发送 api 请求的最佳位置。

例如:

import React from 'react';
import instance from '../../api';

class QuestionList extends React.Component {
    constructor() {
        super();
        this.state = {
            data: [],
        };
    }

    componentDidMount() {
        instance.get('/questions').then((res) => {
            this.setState({ data: res.data });
        });
    }

    render() {
        const { data } = this.state;
        return (
            <div>
                {data &&
                    data.map((d) => {
                        return (
                            <div>
                                question: {d.question}, tags: {d.tags}
                            </div>
                        );
                    })}
            </div>
        );
    }
}
export default QuestionList;

【讨论】:

  • 我关注了这个,但是我的本地主机没有显示任何内容
  • 如果你能解释一下那些正在映射的花括号的含义
  • 我认为你对 React 很基础。它只是向你展示如何使用数据,你必须在 render() 函数中返回一些东西。您可以在花括号之间编写 javascript 代码
  • 我按照你的代码,它向我显示了这个错误:解析错误:意外的令牌,预期的“;”在 componentDidMount(){...}
  • 代码可能有语法问题 :) 如果您认为修复起来并不容易,请在此处发布
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 2016-06-20
  • 2017-05-27
  • 1970-01-01
相关资源
最近更新 更多