【问题标题】:How to fetch and map api response data using axios如何使用 axios 获取和映射 api 响应数据
【发布时间】:2021-12-02 12:20:11
【问题描述】:

向 API 发送请求并在控制台中获取 API 响应,返回数据将为 object

API RESPONSE:

参考这里:Json API response

现在如何使用 axios 在网页上显示数据。下面的代码展示了如何调用API

import React, { Component } from 'react'
import axios from 'axios'

class PostForm extends Component {
    constructor(props) {
        super(props)

        this.state = {
            key: '10-10-21',
            // Where data will be saved.
            data: [],
        }
        console.log(this.state)
    }

    changeHandler = e => {
        this.setState({ [e.target.name]: e.target.value })
    }

    submitHandler = e => {
        e.preventDefault()
        
        axios
        .get(`http://127.0.0.1:8000/hgetall_hash?key=${this.state.key}`)
        .then(response => {
                        // Updating the state to trigger a re-render       
            this.setState({data: response.data});
            console.log(response.data)
        })
        .catch(error => {
            console.log(error)
        })
    }

    render() {
        const { key } = this.state
        
        return (
            <center><div>
                <form onSubmit={this.submitHandler}>
                    <div>
                        <h2> DATE PICKER</h2><br></br>
                        <input
                            type="text"
                            name="key"
                            value={key}
                            onChange={this.changeHandler}
                        />                        
                    </div>
                    <br></br>
                    <button type="submit">Submit</button>
                </form>
            </div></center>
        )
    }
}
export default PostForm

从此代码将响应存储在变量和映射中,在网格视图中显示数据。

【问题讨论】:

  • 你可以在返回的 jsx 中的某处使用 {this.state.data.map(item => {map your item here, don't forget the key}}
  • 另外,
    标签在 HTML5 中已被弃用,而
    标签是自关闭的。最后,您的更改处理程序需要在构造函数中重新绑定到“this”
  • @DovRine 你能用我的代码解释一下我想在显示器上获取时间和视频吗

标签: javascript node.js reactjs api axios


【解决方案1】:

响应将存储在您在 this.state 中定义的数据中。

this.state.data.map((item)=>( {item.time} )) 显示是网格,您可以使用 display: grid

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 2021-07-27
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
相关资源
最近更新 更多