我将react
和redux toolkit
与redux-persist
一起使用。当在useEffect
中发出http
请求时,即使数据不变,它也会导致组件无限次重新渲染,所以问题出在useSelector
中,我甚至尝试过shallowEqual
函数,也没有严格模式,但它不起作用。
import { createSlice } from '@reduxjs/toolkit';
const cartReducer = createSlice({
name: 'cart',
initialState: {
ids: [],
},
reducers: {
cartAction: (state, action) => {
const checkId = state.ids.findIndex((item) => item === action.payload);
if (checkId === -1) {
state.ids = [...state.ids, action.payload];
}
},
},
});
import { configureStore } from '@reduxjs/toolkit';
import { combineReducers } from 'redux';
import storage from 'redux-persist/lib/storage';
import { persistReducer } from 'redux-persist';
import {
persistStore,
FLUSH,
PAUSE,
REGISTER,
PERSIST,
REHYDRATE,
PURGE,
} from 'redux-persist';
import cartReducer from '../redux/cartRedux';
const reducers = combineReducers({
cart: cartReducer,
});
const persistConfig = {
key: 'cartItems',
storage,
};
const persistedReducer = persistReducer(persistConfig, reducers);
const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [REGISTER, FLUSH, PAUSE, PERSIST, REHYDRATE, PURGE],
},
}),
});
let persistors = persistStore(store);
import { useSelector, shallowEqual } from 'react-redux';
let cartItemsId = useSelector((state) => state.cart.ids, shallowEqual);
const [loading, setLoading] = useState(false);
const [products, setProducts] = useState([]);
useEffect(() => {
const getCartProductsById = async () => {
setLoading(true);
return await axios
.post('/getMultipleProducts', cartItemsId)
.then((response) => {
setLoading(false);
setProducts(response.data);
console.log(products);
})
.catch((error) => {
setLoading(false);
console.log(error);
});
};
getCartProductsById();
}, [cartItemsId,products]);
这与Redux完全无关。
您的无限循环是由setProducts(response.data);
与依赖数组组合引起的。
您的useEffect
将products
作为依赖项,因此如果products
发生更改,它将向服务器发出一个新请求,在该请求集之后,这些产品将成为一个新对象,即使该对象具有相同的内容。因此,依赖关系发生了变化,从而触发了useEffect
的新周期。