【问题标题】:Why i don't get the data from the api in React?为什么我没有从 React 中的 api 获取数据?
【发布时间】:2021-03-25 18:00:59
【问题描述】:

我正在尝试从我的 api 获取 componentValue,但它不起作用。我在终端或控制台中没有收到任何错误。

这是我的 api 提供的 json:

 [
    {
    id: 100,
    componentName: "bp",
    componentValue: "120/80",
    measuredDateTime: null
    },
    {
    id: 102,
    componentName: "bp",
    componentValue: "120/80",
    measuredDateTime: null
    },
    {
    id: 107,
    componentName: "bp",
    componentValue: "50/60",
    measuredDateTime: null
    },
    {
    id: 30,
    componentName: "bp",
    componentValue: "90/149",
    measuredDateTime: "2018-03-19T18:34:24.000+00:00"
    }
    ]

这是我的反应代码:

import React from 'react';
import axios from 'axios';
class ChartGenerator extends React.Component{

    state={
        clinicalData:[]
    }

    componentDidMount(){
        axios.get("http://localhost:8080/clinicalservices/api/clinicals/1/bp").then(res=>{

            this.setState(res.data);
        })

    }


    render(){
        return (<div>
            <h2>Clinical Report:</h2>
            {this.state.clinicalData.map((item,index)=>(
                <p key={index}>{item.componentValue}</p>
            ))}

        </div>);
    }
}



export default ChartGenerator;

我尝试了所有方法,但没有成功! 如果你知道什么请帮助我!

【问题讨论】:

    标签: reactjs api axios


    【解决方案1】:

    您尝试设置state 的方式是错误的。你应该像这样设置你的state

    this.setState({ clinicalData: res.data });
    

    【讨论】:

      【解决方案2】:

      state 是一个object,所以当你设置它时,你也应该将它设置为objectres.data 是一个数组。

      this.setState({clinicalData: res.data})
      

      应该这样做

      【讨论】:

        猜你喜欢
        • 2022-11-23
        • 2011-11-08
        • 1970-01-01
        • 2023-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-24
        相关资源
        最近更新 更多