我在使用上下文API和钩子方面还很新。我所面临的问题是,即使将对象传递给它,使用useReducer的引用传递动作的分派时,初始状态也没有更新。代码如下:reducer.js
export const initialState={
basket:[ ],
}
const reducer= (state= initialState, action) => {
console.log(action);
switch(action.type) {
case 'ADD_TO_BASKET':
return {
...state,
basket:[...state.basket,action.item]
};
case 'REMOVE_FROM_BASKET':
//we cloned the basket
let newBasket = [...state.basket];
const index= state.basket.findIndex((basketItem) => basketItem.id === action.id);
if (index >= 0) {
//item exist in basket , remove it
newBasket.splice(index, 1);
} else {
console.warn (
'cant remove product (id: ${action.id}) as its not in basket'
);
}
return {...state, basket: newBasket,};
break;
default:
return state;
}
}
export default reducer;上面的console.log(action)给出了item: {…} id: "101" image: "https://images.pexels.com/photos/534/animal-countryside-agriculture-farm.jpg" price: 11.96 rating: 5 title: "dress1" <prototype>: Object { … } type: "ADD_TO_BASKET" <prototype>: Object { … },因此对象被传递给还原器,但是初始状态没有更新。只有case:ADD_TO_BASKET不适用于另一种情况: REMOVE_FORM_BASKET运行得很好,如果有人能帮助我,.I会很感激的。
这是其他供参考的文件。stateProvider.js
//we need this to track the basket
//setup data layer
import React, { createContext , useContext, useReducer } from "react";
import reducer, {initialState} from './reducer';
//this is the data Layer
export const StateContext = createContext();
//BUILD a provider
export const StateProvider = ({children}) =>{
const state = useReducer(reducer, initialState);
return (
<StateContext.Provider value={state}>
{children}
</StateContext.Provider>
);
}
//this is how we use it inside of a component
export const useStateValue = () =>useContext(StateContext);product.js
import { useStateValue } from './StateProvider';
import "./product.css";
function Product ({id,title,image,price,rating}){
const [{}, dispatch] = useStateValue();
const addToBasket =() => {
console.log("am clicked");
dispatch({
type: 'ADD_TO_BASKET',
item: {
id: id,
title: title,
image: image,
price: price,
rating: rating
},
});
};
return (......
......
.....header.js
import "./Header.css";
import {Link} from "react-router-dom"
import { useStateValue } from './StateProvider';
function Header() {
//const [state,dispach] = useStateValue();
const [{basket,user}] = useStateValue();
console.log(basket);
return(
<div>
.
.
.
<Link to="/checkout" className="header_link">
<div className="header_optionbasket">
<ShoppingBasketIcon/>
<span className="header_optiontwo basketcount">{basket.length}</span>
</div>
</Link>
.
.
.
</div>
)在初始状态更新后,basket.length in header.js是想要更新的,但是它仍然是0,但是如果我在initialState>basket中硬编码一个对象,那么basket.length将被更新。但是对象并没有被添加到InitialState >中
发布于 2020-09-09 07:02:57
export const initialState={
basket:[ ],
}
const reducer= (state=initialState, action) => {
console.log(action);
switch(action.type) {
case 'ADD_TO_BASKET':
return {
...state,
basket:[...state.basket,action.item]
};你必须在还原器中初始化状态。另外,您也不需要在减速机中添加中断语句。
https://stackoverflow.com/questions/63806280
复制相似问题