我对在react中使用上下文API和挂钩相当熟悉。在尝试使用引用useReducer
传递操作调度时,我遇到了一个问题,即初始状态没有更新,但对象已传递给它。代码如下:减速器.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;
上面的CCD_ 2给出CCD_。只有情况:ADD_TO_BASKET不起作用,另一种情况:REMOVE_FORM_BASKET工作正常。如果有人能帮我,我将不胜感激。
这是其他文件供参考。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>
)
初始状态更新后,header.js中的basket.length被允许更新,但它仍然为0,但如果我在initialState>basket,则更新basket.length。但是对象没有被添加到InitialState>吊篮
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]
};
您必须在reducer中初始化状态。此外,您不需要在reducer中添加Break语句。