首页 > 解决方案 > Conditional set state in React

问题描述

I have this component that changes background color based on the school's rating.

Between 1 to 10, if the school's rating 3 and below should be orange, between 4 and 7 and should be yellow, 8 and above should be green. If the school does not have a rating (null), should be gray.

Here's my attempt:

...

  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>
    )
  }

...

But now everything is green, even though I tested with various numbers.

What am I doing wrong?

标签: javascriptreactjstypescript

解决方案


See the Rules of Hooks and the code samples within. useState must be called within the body of your component, like this:

const Single = ({rating, name, distance}: Single) => {
    const [bg, setBg] = useState('gray')

    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>
    )
  }

推荐阅读