export default function SurveyReducer(state, action) {
console.log("state =>", state);
console.log("action =>", action);
if (state === undefined) {
return { clickedArray: [] };
}
var newState;
switch (action.type) {
case "ADD_SURVEY":
var newData = { id: action.data };
newState = {
...state,
clickedArray: state.clickedArray.push(newData),
};
break;
case "DELETE_SURVEY":
newState = {
...state,
clickedArray: state.clickedArray.filter(
(item) => item.id !== action.data.id
),
};
break;
default:
break;
}
return newState;
}
array state에 값을 추가하고 싶었다.
array state가 1로 대체된다...
1. 일단 이렇게 하면 되긴 한다.
export default function SurveyReducer(state, action) {
console.log("state =>", state);
console.log("action =>", action);
if (state === undefined) {
return { clickedArray: [] };
}
var newState;
switch (action.type) {
case "ADD_SURVEY":
var newArray = [];
var newData = { id: action.data };
state.clickedArray.map((item) => newArray.push(item));
newArray.push(newData);
newState = {
...state,
clickedArray: newArray,
};
break;
case "DELETE_SURVEY":
var newArray = [];
var newData = { id: action.data };
state.clickedArray.map((item) =>
item.id !== newData.id ? newArray.push(item) : ""
);
newState = {
...state,
clickedArray: newArray,
};
break;
default:
break;
}
return newState;
}
state 원본값을 바꾸지않고 newArray를 만들어줘서 여기에 push해줬다.
immutable에 대해 알아보자
www.opentutorials.org/module/4075
2. 왜 state를 배열로 쓰려고하는것이냐
Redux에서 제시하는 state 형태
redux.js.org/recipes/structuring-reducers/normalizing-state-shape
Normalizing State Shape | Redux
Structuring Reducers > Normalizing State Shape: Why and how to store data items for lookup based on ID
redux.js.org
"store도 하나의 db이다"
state에 대한 설계가 필요하다.
'개발일지 > React' 카테고리의 다른 글
Redux 입문하기 (with React.js) (0) | 2021.09.28 |
---|---|
Next.js (0) | 2020.08.01 |
[React] 개발환경 설정 (0) | 2020.07.11 |