英文:
How to keep checkbox ticked on reload page using value from searchParams
问题
我从queryParams中获取`discount`值,如我在顶部的注释中所述。
我尝试在输入字段中添加这行代码
checked={discountOption === discountFromQueryParams || discountOption === discount}
但是在重新加载时,它无法保持特定折扣值的`checked`状态。但是,在queryParams中,这个值在重新加载时会保留。在这里,我应该如何保持复选框的选中状态?
英文:
My component looks like this
function FilterDiscounts({ discount, handleDiscounts }) {
const discountsList = Array.from({ length: 9 }, (_, index) => (index + 1) * 10);
const [isChecked, setIsChecked] = useState(false)
// const [queryParams] = useSearchParams();
// const discountFromQueryParams = queryParams.get('discount')
const handleChange = (discountValue) => {
if(isChecked && discount === discountValue) {
setIsChecked(false)
handleDiscounts(null)
} else {
setIsChecked(true)
handleDiscounts(discountValue)
}
}
return (
<Row>
<h6>DISCOUNT RANGE</h6>
{
discountsList.map((discountOption, index) => {
return (
<div key={index} className="filter-type">
<input
type="checkbox"
checked={discountOption === discount}
onChange={() => handleChange(discountOption)}
/>
<div className="filter-item">{discountOption}% and above</div>
</div>
)
})
}
</Row>
);
}
I get the discount
value from queryParams as i've commented at top.
I tried adding this line
checked={discountOption === discountFromQueryParams || discountOption === discount}
in input field but it does not retain checked
state of a particular discount value on reload. However, in queryParams, this value will be there on reload also.
How can i keep the checkbox checked on reload here ?
答案1
得分: 0
问题出在discountOption
的类型是Number
,而discountFromQueryParams
的类型是string
,我在使用===
运算符。
在这里更改了一些代码行:
const discountFromQueryParams = Number(queryParams.get('discount'))
...
if((isChecked && discountValue === discount) || (discountValue === discountFromQueryParams)) { ... }
...
checked={discountOption === discountFromQueryParams || discountOption === discount}
英文:
The problem was with types of discountOption
- Number
and discountFromQueryParams
- string
and i was using ===
operator.
Changed these few lines here to
const discountFromQueryParams = Number(queryParams.get('discount'))
...
if((isChecked && discountValue === discount) || (discountValue === discountFromQueryParams)) { ... }
...
checked={discountOption === discountFromQueryParams || discountOption === discount}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论