[英]Why am i getting this error 'TypeError: state is not iterable' on react and redux
I'm trying since a few hours and still getting the same error "TypeError: state.codes is not iterable" when declaring the reducer几个小时后我一直在尝试,但在声明减速器时仍然遇到相同的错误“TypeError:state.codes is not iterable”
The idea behind my file is to pass a value (code) for ex.我的文件背后的想法是为 ex 传递一个值(代码)。 '12345' with dispatch into the reducer and be able to update an array _codeData every time when a new dispatch has taken place.
'12345' 分配到 reducer 中,并且每次发生新的分配时都能够更新数组 _codeData。
anyone have any idea?有人知道吗?
thanks in advance:),提前致谢:),
File1.js文件1.js
function BarcodeScanner() {
const initialState = {
code: ''
};
const [state, dispatch ] = useReducer(reducer, initialState);
function handleScan(code){
dispatch({
type: 'ADD_CODE',
payload: {
code,
},
});
}
File2.js文件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]);
I guess you're trying to spread an undefined or null value.我猜您正在尝试传播未定义或 null 值。 To solve this issue you can use the Logical OR operator.
要解决此问题,您可以使用逻辑或运算符。
PS: If the value was always null/undefined, ensure your reducer is working correctly first. 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.