useReducer action.data not iterable 오류 해결
8349 단어 ReactuseReducerReact
상황
dispatch를 이용하여 dispatch의 data들을 reducer에게 action으로 보내주는 상황
const reducer = (state,action) => {
let newState = [];
switch(action.type){
case 'CREATE':{
newState = [...action.data, ...state]; //
break; // break걸지 않으면 자동으로 default가 실행된다.
}
default:
return state;
}
return newState;
};
const onCreate = (author, content, picture) => {
dispatch({type : "CREATE",
data: {
id: dataId.current,
author,
content,
picture,
}})
dataId.current += 1;
};
- onCreate의 매개변수들을 전달받아 action으로 reducer에게 전달한다.
- 그러나 TypeError가 발생한다.
action.data 즉, type과 함께 전달한 data들이 전달될 수 없다고 나온다.
const [data,dispatch] = useReducer(reducer,dummyData);
그래서 reducer에서 설정한 data들은 어떤 형식으로 있는지 살펴보았다.
그렇다 배열안에 객체형식으로 있던 것이다!!!
const onCreate = (author, content, picture) => {
dispatch({type : "CREATE",
data: {
id: dataId.current,
author,
content,
picture,
}})
dataId.current += 1;
};
action.data는 이미 객체이다. 그런데 newState에 spread로 뿌려주었다.
그래서 오류가 뜬 것이다.
const reducer = (state,action) => {
let newState = [];
switch(action.type){
case 'CREATE':{
newState = [action.data, ...state]; //
break; // break걸지 않으면 자동으로 default가 실행된다.
}
default:
return state;
}
return newState;
};
위와같이 action.data에 spread연산자를 사용하지 않으면 잘 작동한다.
주의
action.data 옆에 state는 아래와 같다.
배열로 묶여있으므로 새로운 데이터와 합쳐주려면 spread를 사용하여야 한다.
Author And Source
이 문제에 관하여(useReducer action.data not iterable 오류 해결), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@minho100227/useReducer-action.data-not-iterable-오류-해결저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)