[英]Why am i getting this error 'TypeError: state is not iterable' on react and redux
幾個小時后我一直在嘗試,但在聲明減速器時仍然遇到相同的錯誤“TypeError:state.codes is not iterable”
我的文件背后的想法是為 ex 傳遞一個值(代碼)。 '12345' 分配到 reducer 中,並且每次發生新的分配時都能夠更新數組 _codeData。
有人知道嗎?
提前致謝:),
文件1.js
function BarcodeScanner() {
const initialState = {
code: ''
};
const [state, dispatch ] = useReducer(reducer, initialState);
function handleScan(code){
dispatch({
type: 'ADD_CODE',
payload: {
code,
},
});
}
文件2.js
const initialState = {
codes: []
};
export const reducer = (state, action) => {
if (action.type === 'ADD_CODE') {
return {
...state,
codes: [...state.codes, action.payload.code],
};
}
return state;
};
export default function ScannerResultTable() {
const [state, dispatch] = useReducer(reducer, initialState);
const [_codeData, setCodeData] = useState([]);
useEffect(() => {
setCodeData([...state.codes]);
}, [state.codes]);
我猜您正在嘗試傳播未定義或 null 值。 要解決此問題,您可以使用邏輯或運算符。
PS:如果該值始終為 null/undefined,請首先確保您的 reducer 正常工作。
const initialState = {
codes: []
};
export const reducer = (state, action) => {
if (action.type === 'ADD_CODE') {
return {
...state,
codes: [(...state?.codes || []), action.payload.code],
};
}
return state;
};
export default function ScannerResultTable() {
const [state, dispatch] = useReducer(reducer, initialState);
const [_codeData, setCodeData] = useState([]);
useEffect(() => {
setCodeData([(...state?.codes || [])]);
}, [state.codes]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.