#react-native #react-redux #react-hooks
#react-native #react-redux #реагирующие перехваты
Вопрос:
Я пытаюсь обновить состояние в react-redux с помощью перехватов при нажатии кнопки.
При нажатии кнопки обновляется массив ordersArray, и мне нужно обновить этот массив в состоянии redux.
В настоящее время я использую приведенный ниже код, и мой массив состояний остается неизменным без каких-либо изменений.
useEffect(() => {
if (!_.isEmpty(tempOrders)) {
// console.log('tempOrderstempOrders', tempOrders);
dispatch(storeCartOrders(tempOrders));
}
}, [dispatch, tempOrders]);
cartOrderSlice.js
import {createSlice, createAsyncThunk} from '@reduxjs/toolkit';
const slice = createSlice({
name: 'cartOrder',
initialState: {
cartOrders: [],
},
reducers: {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
storeCartOrders: (state, action) => {
console.log('action.payload', action.payload) // <-- this payload always has old values
state.cartOrders = action.payload;
},
},
});
export const {storeCartOrders} = slice.actions;
export default slice.reducer;
-
Ниже
useEffect
вызывается при нажатии кнопки -
Ниже будет
setTempOrders
useEffect, который, в свою очередь, вызоветuseEffect
перехват сdispath
функциейuseEffect(() => { const updateOrders = async () => { let rows = [...tempOrders]; if (currentItemValues) { const currentItemIndex = rows.findIndex( (row) => row.id === currentItemValues.id, ); if (currentItemIndex >= 0) { if (currentItemValues.quantity === 0) { rows.splice(currentItemIndex, 1); } else { rows[currentItemIndex]['quantity'] = currentItemValues.quantity; } } } // console.log('rowsrowsrows', rows); // rows[currentItemIndex]['quantity'] is not being changed at all. // and that's why storage and setTempOrders won't change the data. setTempOrders(rows); await setLocalCartItems('cart', rows); }; if (!_.isEmpty(tempOrders)) { updateOrders(); } }, [currentItemValues, toggle]);
Пожалуйста, дайте мне знать, если вам нужно показать больше кода.
Ваша помощь очень ценится! Спасибо
Иногда это выдает ошибку типа :
Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot assign to read only property 'quantity' of object '#<Object>'
Комментарии:
1. можете ли вы показать свой код нажатия кнопки? если у вас есть нажатие кнопки, зачем вам использовать useEffect, когда вы можете просто вызвать отправку по щелчку?
2. Я обновил вопрос и заголовок, он вызывается из useEffect. извините за путаницу.
3. какое текущее значение перед вызовом настроек (строк)?
4. значение currentItemValues .
5. Я обновил вопрос. на самом деле я понимаю, что это может быть не связано с тем, что функция отправки не обновляет состояние. это скорее массив, который не обновляет строки значений [currentItemIndex][‘quantity’] = currentItemValues . количество; пожалуйста, посмотрите на изображение и узнайте, что количество было равно 3, но оно не было изменено после обновления строк.
Ответ №1:
у вас есть массив для object, поэтому вам нужно выполнить следующее
rows[currentItemIndex].quantity = currentItemValues.quantity;