react/redux工具箱useSelector在存储状态更改时不更新



hi我有一个cart切片,当我用disptach将对象推送到它时,状态会更新,但当将它映射到cart组件中以显示为列表时,它不会更新!如果我做了那么愚蠢的事,请原谅我!

推车切片:

import { createSlice } from '@reduxjs/toolkit'
const CartSlice = createSlice({
name: 'cart',
initialState: {
cart:[{name:"cart item",price:"15",qt:1},]
},
reducers: {
additem: (state,action) => {
state.cart=[...state.cart,action.payload]
},

}
})
export const {additem} = CartSlice.actions
export default CartSlice.reducer

存储:

import { configureStore } from '@reduxjs/toolkit'
import RestaurantsReducer from './Slices/RestaurantsSlice'
import CartReducer from './Slices/CartSlice'
export default configureStore({
reducer: {
Restaurant:RestaurantsReducer,
Cart:CartReducer
},
})

推车组件:

import React from "react";
import { useSelector } from "react-redux";
import {ListGroup} from 'react-bootstrap'
function Cart() {
let items = useSelector((state) => state.Cart.cart);
console.log(items)
return (
<div>
<ListGroup>
{items.map((item) => (
<ListGroup.Item>{item.name} {item.price} * {item.qt}</ListGroup.Item>
))}
</ListGroup>
</div>
);
}
export default Cart;

板条箱项目被推到这样:

const dispatch=useDispatch();
dispatch(additem({name:item.name,price:item.price,qt:1}))

根据文档示例,传递给reducer函数的state似乎是一个immer对象,因此您可以执行以下操作:

additem: (state,action) => {
state.cart.push(action.payload)
},

如immer文档中所述。

相关内容

  • 没有找到相关文章

最新更新