javascript - 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?
解决方案
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>
)
}
推荐阅读
- python - 我如何在 PyTorch 中为鼻窦实现 __getitem__ 方法
- javascript - 如何在 redux 中保存图像和视频文件
- python - 如何使用 pandas 或任何简单方法将列表的嵌套字符串表示形式转换为 python 中的列表?
- python - 使用注册应用程序时未显示表单
- excel - 如何在所有条件中使用带有 OR 逻辑的 sumifs?
- r - 无法连接到 Google Cloud Platform JupyterLab 笔记本上的 R 内核
- java - 使用 SpringFox/Swagger 在库中记录类的问题
- android-backup-service - 是否可以制作自己的传输以插入 Android BackupManager 服务?
- android - 如何将 libjsoncpp 链接到 AOSP 的 healthd?
- python - 为什么会有这个警报?原因和排除