[英]Can't use array functions like .includes in Object literals
我試圖在由數組組成的對象文字中組織我的反應狀態。
const [state, setState] = React.useState({ filter: [], other: [] });
每當單擊列表項時,我都想更新我的過濾器數組。
const handleListItemClick = (event, index) => {
if (state['filter'].includes(index)) {
setState(state['filter'].filter(function (element) {
return element != index;
}))
} else {
setState(state['filter'].concat([index]));
}
};
但是每當我嘗試訪問過濾器數組時,java 腳本都無法解析包含或 indexOf 之類的數組函數,例如:
<ListItem
button
selected={state['filter'].includes(0)}
onClick={(event) => handleListItemClick(event, 0)}>
<ListItemText primary="Kundensegmente" />
</ListItem
我收到此錯誤:
未捕獲的類型錯誤:state.filter.includes 不是函數
使用 include 之類的函數似乎可以在一維數組中使用。
狀態的原始形狀是這樣的:
{ filter: [], other: [] }
但后來你改變了它:
setState(state['filter'].concat([index]));
您將整個狀態替換為與新數組[index]
的fiter
(一個空數組)的值。
那個新數組沒有filter
屬性。
對filter
和other
使用單獨的狀態。
const [filter, setFilter] = React.useState([]);
const [other, setOther] = React.useState([]);
或者,如果您真的希望將它們合並為一個對象,那么您需要在狀態中保持該對象的形狀。
創建一個與舊對象相同的新對象,只是要更改的位除外。
setState({
...state,
filter: state.filter.concat([index]);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.