0

我在反应中使用上下文 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 { … }结果是对象被传递给reducer,但初始状态没有更新。只有这种情况: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);

产品.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 > 篮子中

4

1 回答 1

1
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 中添加 Break 语句。

于 2020-09-09T07:02:57.750 回答