为什么不导出 reduxjs-toolkit 中的操作? (React Js - redux 工具包)
Why actions in reduxjs-toolkit are not exported ? (Reactjs - reduxToolkit)
我正在使用@reduxjs/toolkit 和 reactjs 构建购物车,当我从 Cart.js 导出操作并尝试将它们导入其他文件,如 cart.jsx 和 header.jsx,它说:
点击调用 addToCart 导入操作的 addTocart 按钮后检查 CONSOLE 时,它显示:
这是cart.js(位于redux文件夹)代码:
import { createSlice } from "@reduxjs/toolkit";
export const cartSlice = createSlice({
name: "cart",
initialState: {
cartProds: []
},
reducers: {
addToCart: (state, {payload})=>{
const exist = state.cartProds.find(prod => prod.id === payload.id);
if(exist){
return state.cartProds.map(prod => prod.id === payload.id ? {...prod, quantity: prod.quantity + 1}: prod);
}
if(!exist){
return state.cartProds = [...state, {...payload, quantity: 1}];
}
},
removeFromCart :(state, {payload}) =>{
const exist1 = state.find( prod => prod.id === payload.id);
if(exist1.quantity === 1){
return state.filter(prod => prod.id !== exist1.id);
}else{
return state.map(prod => prod.id === payload.id ? {...prod, quantity:prod.quantity-1}: prod);
}
}
}
});
export const { addTocart, removeFromCart } = cartSlice.actions;
export default cartSlice.reducer;
这是我导入它们的方式(路径绝对正确!):
import { addToCart, removeFromCart } from '../redux/cart.js';
您已经导出 addTocart
(但是在 createSlice -> reducer 中您有 addToCart
)
export const { addTocart, removeFromCart } = cartSlice.actions;
并导入了addToCart
import { addToCart, removeFromCart } from '../redux/cart.js';
区分大小写!
我正在使用@reduxjs/toolkit 和 reactjs 构建购物车,当我从 Cart.js 导出操作并尝试将它们导入其他文件,如 cart.jsx 和 header.jsx,它说:
点击调用 addToCart 导入操作的 addTocart 按钮后检查 CONSOLE 时,它显示:
这是cart.js(位于redux文件夹)代码:
import { createSlice } from "@reduxjs/toolkit";
export const cartSlice = createSlice({
name: "cart",
initialState: {
cartProds: []
},
reducers: {
addToCart: (state, {payload})=>{
const exist = state.cartProds.find(prod => prod.id === payload.id);
if(exist){
return state.cartProds.map(prod => prod.id === payload.id ? {...prod, quantity: prod.quantity + 1}: prod);
}
if(!exist){
return state.cartProds = [...state, {...payload, quantity: 1}];
}
},
removeFromCart :(state, {payload}) =>{
const exist1 = state.find( prod => prod.id === payload.id);
if(exist1.quantity === 1){
return state.filter(prod => prod.id !== exist1.id);
}else{
return state.map(prod => prod.id === payload.id ? {...prod, quantity:prod.quantity-1}: prod);
}
}
}
});
export const { addTocart, removeFromCart } = cartSlice.actions;
export default cartSlice.reducer;
这是我导入它们的方式(路径绝对正确!):
import { addToCart, removeFromCart } from '../redux/cart.js';
您已经导出 addTocart
(但是在 createSlice -> reducer 中您有 addToCart
)
export const { addTocart, removeFromCart } = cartSlice.actions;
并导入了addToCart
import { addToCart, removeFromCart } from '../redux/cart.js';
区分大小写!