【问题标题】:deal with boolean api in js在js中处理布尔api
【发布时间】:2022-11-03 15:33:56
【问题描述】:

我的一个带有布尔值的 api 响应(名称:used),我的逻辑是如果使用响应将显示red_light 和green_light,如果不使用。

const red_light = <div className="h-2.5 w-2.5 rounded-full bg-red-700 mr-2"></div>
const green_light = <div className="h-2.5 w-2.5 rounded-full bg-green-400 mr-2"></div>

function lighting(code) {
    fetch(`API`)
        .then((response) => {
            if (!response.ok) {
                throw new Error(
                    `This is an HTTP error: The status is ${response.status}`
                );
            }
            return response.json();
        })
        .then((actualData) => {
            return (actualData.used ? red_light : green_light)
        })}

const MembershipLight = (code) => {
    return (
        lighting(code)
    );
};

export default MembershipLight;

但是页面变成空白,我做错了哪一部分?

我尝试使用console.log 和actualData,它显示响应的整个部分,包括used 和true/false,但是当我console.log("actualData.used") 时,它在控制台中显示undefined。

actureData(来自邮递员)

[
    {
        "used": true,
        "create_date": "1644490502",
        "update_date": "1666694655"
    }
]

【问题讨论】:

  • 你也可以加actualData吗?
  • 应该是actualData[0].used ? red_light : green_light
  • 我认为这行不通
  • 它不会因为你没有从函数返回任何东西,如下面的答案......

标签: node.js reactjs


【解决方案1】:

您可能应该更改方法并声明 used 状态以存储返回的布尔值并使用条件渲染来相应地调整类。
此外,正如@KcH 所建议的,如果您的响应是一个数组,您应该使用索引访问该元素:

import { useState, useEffect } from 'react';

const MembershipLight = (code) => {
  const [used, setUsed] = useState(false);

  const lighting = () => {
    fetch(`API`)
    .then((response) => {
      if (!response.ok) {
        throw new Error(
          `This is an HTTP error: The status is ${response.status}`
        );
      }
      return response.json();
    })
    .then((actualData) => {
      if (actualData.length > 0) {
        setUsed(actualData[0].used)
      }
    })
    .catch((err) => console.log(err));
  }

  useEffect(() => {
    lighting();
  }, []);

  return <div className={`h-2.5 w-2.5 rounded-full mr-2 ${used ? 'bg-red-700' : 'bg-green-400'}`}></div>;
};

export default MembershipLight;

【讨论】:

    【解决方案2】:

    此外,您不会从 lighting 函数返回任何内容。您应该返回fetch 的结果。目前,您的MembershipLight 会因此而返回undefined。

    【讨论】:

    • 我试着把let light = ""放在函数下面,light = (actualData.used ? red_light : green_light)放在.then下面,现在页面不是空白的。但照明功能仍然不起作用
    猜你喜欢
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    相关资源
    最近更新 更多