React/TypeScript异步获取LED状态后样式渲染遇TS(1005)错误
问题描述
尝试从服务器读取3个LED状态,页面加载时根据LED开关状态更新显示。目前用async/await、useState和useEffect能正常接收服务器返回的JSON,但设置按钮颜色时出现“'...' expected TS(1005)”错误。需求是:redLedOn为true时按钮背景色设为bg-red-400,为false时设为bg-red-10,但无法将LED状态用于样式切换。
相关代码:
import { useState, useEffect } from 'react' export default function ToggleLED() { const getLed = async () => { try { const webResult = await fetch("/api/get-led"); const myText = await webResult.text(); const ledjson = JSON.parse(myText); // Log the text and JSON console.log(myText); console.log(ledjson); // Return the JSON return ledjson; } catch (error) { console.log(error); } }; const processLedData = async () => { const result = await getLed(); setRedLedOn(result.is_red_led_on); // Log console.log("result.is_red_led_on = " + result.is_red_led_on); console.log("redLedOn = " + redLedOn); } const [redLedOn, setRedLedOn] = useState(processLedData); useEffect(() => { processLedData(); }, []) return ( <> <h1 className="hdrcenter">Click To Toggle</h1> {/* Red button */} <div className="container py-4 px-20 mx-0 min-w-full flex flex-col items-center"> <button className="btnred btn-circle btn-lg h-28 w-28 text-black transition-colors duration-150 hover:bg-red-400 hover:text-black" //{************************************************************* // Need state of led here to toggle background color such as // redLedOn ? 'bg-red-400' : 'bg-red-10' // } // But I get little squiggley here saying '...' expected TS(1005) > Led Off </button> </div> </> ); }
解决方案
问题分析
- useState初始化错误:
useState(processLedData)是错误用法,useState的初始函数参数必须是同步函数,不能传入异步函数,应该给一个初始默认值(比如false)。 - JSX样式语法错误:动态设置className需要在
className属性的大括号内写表达式,不能在属性外写逻辑,这是导致TS(1005)错误的直接原因。 - 状态更新异步性问题:
setRedLedOn是异步操作,执行后立刻打印redLedOn会拿到旧值,需要通过useEffect监听状态变化来查看最新值。
修正代码
import { useState, useEffect } from 'react' export default function ToggleLED() { // 初始化redLedOn为false,后续由接口数据更新 const [redLedOn, setRedLedOn] = useState(false); const getLed = async () => { try { const webResult = await fetch("/api/get-led"); const myText = await webResult.text(); const ledjson = JSON.parse(myText); console.log(myText); console.log(ledjson); return ledjson; } catch (error) { console.log(error); // 出错时返回默认值,避免后续报错 return { is_red_led_on: false }; } }; const processLedData = async () => { const result = await getLed(); setRedLedOn(result.is_red_led_on); console.log("result.is_red_led_on = " + result.is_red_led_on); } useEffect(() => { processLedData(); }, []); // 监听redLedOn变化,打印最新状态 useEffect(() => { console.log("redLedOn = " + redLedOn); }, [redLedOn]); return ( <> <h1 className="hdrcenter">Click To Toggle</h1> {/* Red button */} <div className="container py-4 px-20 mx-0 min-w-full flex flex-col items-center"> <button className={`btnred btn-circle btn-lg h-28 w-28 text-black transition-colors duration-150 hover:bg-red-400 hover:text-black ${redLedOn ? 'bg-red-400' : 'bg-red-10'}`} > {redLedOn ? 'Led On' : 'Led Off'} </button> </div> </> ); }
关键修改点
- 将
useState(processLedData)改为useState(false),给状态一个合法的初始值。 - 用模板字符串整合静态类名和动态类名,把
redLedOn ? 'bg-red-400' : 'bg-red-10'嵌入到className的模板字符串中,解决TS语法错误。 - 新增一个
useEffect监听redLedOn的变化,确保能打印到最新的状态值。 - 按钮文本也根据
redLedOn动态切换,提升交互反馈。
内容的提问来源于stack exchange,提问作者Barry
相关产品推荐
相关产品推荐

