在 React 中发起 http 请求并解析数据

Make an http request and parse the data in React

我正在尝试使用基于 React 的前端向我的后端服务器(运行 on java springboot)发出一个 http 请求,returns 一个我想要的字符串解析并赋值。从我在语法页面上看到的内容,我想相信我正在正确调用请求。我的错误消息提到“无法读取未定义的属性(读取 'split')”,我认为这意味着 split() 不是 js 或 React 的有效操作?有谁知道正确的方法是什么?

import React from 'react';
import './App.css';
import Exchange from './Exchange'
import Recommendations from './Recommendations';
import axios from "axios";


function Middle(){
    const response = axios.get("http://localhost:8080/run");
    const data = response.data;
    const dataArr = data.split(",");
    
    return (

        <div className = 'Middle'>
            <h1>{data}</h1>
           <Exchange name = "Coinbase" btcBuy = {dataArr[1]} btcSell = "" ethBuy = "" ethSell = ""/>
           <Exchange name = "Binance" btcBuy = "" btcSell = "" ethBuy = "" ethSell = ""/>
           <Recommendations/>
        </div>

    );
};
export default Middle;

实际上你没有正确阅读 response,因为它是一个异步操作,你的响应是 undefined 在你对它进行顺序操作时。

您必须将您的代码放在 .then 的正文中,如下所示:

let dataArr = [];
axios.get("http://localhost:8080/run")
    .then(response => {
        const data = response.data;
        dataArr = data.split(",");
    });

这是因为数据还没有设置。 axios returns 承诺您必须为此目的使用 await 。你不应该调用 api 就像 useEffect 是为此目的而构建的

import React from 'react';
import './App.css';
import Exchange from './Exchange'
import Recommendations from './Recommendations';
import axios from "axios";


function Middle(){
    const [data,setData] = React.useState(null)

    useEffect(()=>{
     //will get rid of warning of memory leak
    let mounted = false 
    if(!mounted){
    axios.get("http://localhost:8080/run")
   .then(data=>setData(data))
   .catch(err=>//do something);
    }
   return ()=>mounted= true
   
},[])
    
    
    return (

        <div className = 'Middle'>
            <h1>{data}</h1>
           <Exchange name = "Coinbase" btcBuy = {dataArr[1]} btcSell = "" ethBuy = "" ethSell = ""/>
           <Exchange name = "Binance" btcBuy = "" btcSell = "" ethBuy = "" ethSell = ""/>
           <Recommendations/>
        </div>

    );
};
export default Middle;

表示data变量不是字符串。如果你想获取数据,你还需要使用useEffect。

import React, { useState, useEffect } from "react";

function Middle(){

    const [data, setData] = useState([]);

    useEffect(() => {

      (async () => {
        try {
          const response = await axios.get("http://localhost:8080/run");
          const data = response.data;
          setData(data); // use split if you have to, I dont think you need that.
        } catch(err) {
          console.error(err);
        }
      })()

    }, [])