猿问

React 中的条件设置状态

我有这个组件可以根据学校的评级改变背景颜色。


between 1to 10, if the school's rating 3and below should be orange, between 4and 7and should be yellow, 8and above应该是green。如果学校没有评分(null),应该是gray。


这是我的尝试:


...


  const [bg, setBg] = useState('gray')


  const Single = ({rating, name, distance}: Single) => {

    if (rating && rating <= 3) {

      setBg(`orange`)

    } else if (rating && rating >= 4 && rating <= 7) {

      setBg(`yellow`)

    } else if (rating && rating >= 8) {

      setBg(`green`)

    }


    return (

      <div>

        <span backgroundColor={bg}>

          {rating !== null ? rating : `NA`}

        </span>

      </div>

    )

  }


...

但是现在一切都是green,即使我用各种数字进行了测试。


我究竟做错了什么?


慕妹3242003
浏览 92回答 2
2回答

PIPIONE

你需要useMemo在这里const bg = useMemo(() => {&nbsp; &nbsp; if (rating && rating <= 3) {&nbsp; &nbsp; &nbsp; &nbsp; return 'orange'&nbsp; &nbsp; &nbsp; } else if (rating && rating >= 4 && rating <= 7) {&nbsp; &nbsp; &nbsp; &nbsp; return 'yellow'&nbsp; &nbsp; &nbsp; } else if (rating && rating >= 8) {&nbsp; &nbsp; &nbsp; &nbsp; return 'green'&nbsp; &nbsp; &nbsp; }}, [rating])所以现在useMemo只有当值rating被更改并将返回值保存到时才会调用函数回调const bg如果您希望跨度的背景颜色基于 的值设置bg,则必须更改跨度定义,如下所示<span style={{backgroundColor: bg}}>...

凤凰求蛊

请参阅Hooks 规则和其中的代码示例。useState必须在组件的主体内调用,如下所示:const Single = ({rating, name, distance}: Single) => {&nbsp; &nbsp; const [bg, setBg] = useState('gray')&nbsp; &nbsp; if (rating && rating <= 3) {&nbsp; &nbsp; &nbsp; setBg(`orange`)&nbsp; &nbsp; } else if (rating && rating >= 4 && rating <= 7) {&nbsp; &nbsp; &nbsp; setBg(`yellow`)&nbsp; &nbsp; } else if (rating && rating >= 8) {&nbsp; &nbsp; &nbsp; setBg(`green`)&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <span backgroundColor={bg}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {rating !== null ? rating : `NA`}&nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答