You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中获取Axios接口响应后修改按钮颜色问题求解

问题原因
  • 原llamadaAxiosGet方法没有返回Promise对象,异步请求的状态码无法被外层获取,调用时拿到的是undefined
  • Axios请求是异步执行的,原代码同步读取estado判断颜色时,接口请求还未返回,拿不到真实状态码
  • 错误处理逻辑存在问题:Axios捕获的错误对象中,状态码存放在error.response.status字段,直接读取error.status会得到undefined
  • 子组件中存在多余的setEstado(props.llamada)调用,props并没有传入llamada属性,会覆盖正确的状态值
完整修改代码
import React, { useState, useEffect } from "react";
import "./../App.css";
import axios from "axios";
const MicroService = (props) => {
  const [personsGet, setPersonGet] = useState([]);

  // 改造1:返回Promise,让外层可以拿到异步结果
  function llamadaAxiosGet (url) {
    return axios
      .get(url)
      .then((res) => {
        setPersonGet(res.data);
        return res.status;
      })
      .catch(function (error) {
        // 改造2:正确获取错误状态码,无返回值时默认归为500错误
        return error.response?.status || 500;
      });
  }

  return (
    <div>
      <h2>Microservicio:</h2>
      <BotonLlamada
        url={`https://jsonplaceholder.typicode.com/users`}
        textBoton={"Llamada al servicio y display all"}
        llamadaAxiosGet={llamadaAxiosGet}
      />
      {personsGet.map((person) => (
        <li key={person.name}>{person.name}</li>
      ))}
    </div>
  );
};

function BotonLlamada(props) {
  const [colorButon, setColorButon] = useState("");
  const [estado , setEstado]= useState(0);

  // 改造3:用async/await等待异步请求返回后再更新状态
  const onClickbuton = async () => {
    const status = await props.llamadaAxiosGet(props.url);
    setEstado(status);
  };

  useEffect(() => {
    if (estado > 399) {
      setColorButon("buttonRed");
    } else if (estado === 200) {
      setColorButon("buttonGreen");
    }
  },[estado]);
  return (
    <div>
      <button onClick={onClickbuton} className={colorButon}>
        {props.textBoton}
      </button>
      <br />
    </div>
  );
}

export default MicroService;
补充样式配置

需要提前在App.css中定义好对应的按钮类样式:

.buttonGreen {
  background-color: green;
  color: #fff;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
}
.buttonRed {
  background-color: red;
  color: #fff;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
}

内容的提问来源于stack exchange,提问作者David_Garcia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:06:06