我正在构建一个必须具有状态的菜单,因此我可以稍后跟踪它是否打开。所以我决定使用反应useState(),现在我确实有一个问题,我不能更新这样的状态在我的JSX:
{filterOpenState[`${filterTab.id}`] == true ? <TiTimes /> :<BiDownArrowAlt />}
在这一行我得到了另一个错误:Element implicitly has an 'any' type because index expression is not of type 'number'.
我是这样定义状态和接口的:
type filterOpenStateI = {
[key: string]: boolean
}
const filterOpenState = useState<filterOpenStateI >({
filterType: false,
filterFlag: false,
filterPriceRange: false,
})
const handleMenuState = (e: any)=>{
e.preventDefault();
const filterTabId = e.target.closest('div').id
// Switch the value from state
filterOpenState[filterTabId] = !filterOpenState[filterTabId]
}
我不确定我是否这样做,因为我应该filterOpenStateI
工作时,我定义了filterOpenState
没有useState,但只有一个字典。但是在dict改变之后,react组件渲染了同样的东西,因为我猜这并没有强制react重新渲染?我如何解决这个问题?
filterOpenState是不可变的,你只允许通过函数setState来修改它。在你的代码中,有两个错误
- useState返回一个数组,其中第一项是对象,第二项是setState函数。
- 您正在尝试直接重新分配它的值。这是错误的方式。