#reactjs #react-redux
Вопрос:
Я только что изучил redux и попытался создать простое приложение для магазина с помощью React Redux. все было хорошо, пока я не попробовал объединить редукторы
Когда я нажимаю, чтобы очистить корзину, я получаю ошибку «Ошибка типа: Присвоение постоянной переменной».
вот мой код перед
index.js
function cartReducer(state, action) { switch (action.type) { case ADD_TO_CART: { return { cart: [ ...state.cart, { product: action.productInfo, quantity: action.quantity, }, ], }; } case CLEAR_CART: { const new_state = { ...state }; new_state.cart = []; return new_state; } default: return state; } }
store.js
function loadState(){ try{ const state = localStorage.getItem('cart'); if(state !== null){ return JSON.parse(state); } } catch(e){ // ignore errors } return { cart: [] }; } const store = createStore( cartReducer, loadState(), compose( applyMiddleware(thunk), window.__REDUX_DEVTOOLS_EXTENSION__ amp;amp; window.__REDUX_DEVTOOLS_EXTENSION__() ) );
а вот после комбайновых редукторов
index.js
export default function cartReducer(state, action) { switch (action.type) { case ADD_TO_CART: { return [ ...state, { product: action.productInfo, quantity: action.quantity } ] } case CLEAR_CART: { const new_state = [...state]; new_state = []; return new_state; } default: { if (state === undefined) return []; return state; } } }
store.js
function loadState(){ try{ const state = localStorage.getItem('cart'); if(state !== null){ return JSON.parse(state); } } catch(e){ // ignore errors } return { cart: [] }; } const appReducers = combineReducers({ cart: cartReducer, }); const store = createStore( appReducers, loadState(), compose( applyMiddleware(thunk), window.__REDUX_DEVTOOLS_EXTENSION__ amp;amp; window.__REDUX_DEVTOOLS_EXTENSION__() ) );
Ответ №1:
case CLEAR_CART: { const new_state = [...state]; // new_state is a constant new_state = []; // you can not assign it again return new_state; } // TO FIX IT: case CLEAR_CART: { return []; // that's enough }
Ответ №2:
case CLEAR_CART: { const new_state = [...state]; //clone new_state = []; return new_state; }
Проблема в том, что вы перезаписываете «const new_state».
case CLEAR_CART: { return []; }
Попробуйте вместо этого вот это.