【问题标题】:UseSelector returns undefinedUseSelector 返回未定义
【发布时间】:2021-10-10 11:44:26
【问题描述】:

这种和平的代码可以查看包含用户下注的购物车的状态

const { games } = useSelector((state: any) => state.cart) 我像这样传递给另一个组件

<AppRecentUserGame games={games} filter={gameChoice} />

它应该在主页上接收这个游戏常量,然后按类型或不呈现该投注列表过滤器

interface AppRecentUserGameProps {
  games: Bet[];
  filter: GameTypes;
}

export const AppRecentUserGame = ({
  games,
  filter
}: AppRecentUserGameProps) => {
  const [filterGame, setFilterGame] = useState("");
  useEffect(() => {
    setFilterGame(filter.type);
  }, [filter]);

  const filteredGames = () => {
    if (filterGame === "") {
      return !!games.length ? (
        games.map((game: any) => (
          <CartItem key={game.id} color={game.color}>
            <p>{formatNumberInArray(game.gameNumbers)}</p>
            <div>
              <p>
                {dateFormatValue(new Date(game.betDate))} - (
                {priceFormatted(game.price)})
              </p>
            </div>
            <strong>{game.type}</strong>
          </CartItem>
        ))
      ) : (
        <EmptyContainer>
          <EmptyCart />
        </EmptyContainer>
      );
    } else if (games && filter) {
      const filterGame = games.filter((game) => game.type === filter.type);
      return filterGame.map((game: any) => (
        <CartItem key={game.id} color={game.color}>
          <p>{formatNumberInArray(game.gameNumbers)}</p>
          <div>
            <p>
              {dateFormatValue(new Date(game.betDate))} - (
              {priceFormatted(game.price)})
            </p>
          </div>
          <strong>{game.type}</strong>
        </CartItem>
      ));
    }
  };

  return <>{filteredGames()}</>;
};

每当用户保存他所做的赌注时,必须将组 os 赌注填充到 cartSlice 中,然后所有的赌注都将用于向用户显示他在主页上所做的赌注列表 这是我处理保存过程的方式

const [cartsGames, setCartGames] = useState<Bet[]>([])  
const saveGame = () => {
    try {
      if (totalPrice < 30) {
        const minPrice = gameType["min-cart-value"] 
        throw new Error(
          `Adicione pelo menos ${priceFormatted(minPrice)} em Apostas`)
      }
      cartsGames.forEach((game) => {
        dispatch(CartActions.addToCart(game)) 
        console.log(game)
      }) 
      setCartGames([]) 
      setMessageToUser({
        description: "Aposta Feita, Boa Sorte!",
        color: "var(--spinner)",
        active: true,
      }) 
      setRedirect(true) 
    } catch (error) {
      setMessageToUser({
        description: error.message,
        color: "var(--blue)",
        active: true,
      }) 
    }
  } 

这是我的商店

import { configureStore } from "@reduxjs/toolkit";
import { cartSlice } from "./cartSlc";
import { userSlice } from "./userSlc";
export const store = configureStore({
  reducer: {
    user: userSlice.reducer,
    cart: cartSlice.reducer
  },
}); 

用户切片:


import { SignedUpUserProps } from "../types/userSignup";

const initialState: SignedUpUserProps = {
  users: [
    {
      id: "1",
      name: "test",
      email: "test@gmail.com",
      password: "123456789",
      recentGames: [],
    },

  ],
  isLogged: false,
};

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: { // actions
    createUser(state, action) {
      const newUser = action.payload;
      state.users.push(newUser);
    },
    logIn(state) {
      state.isLogged = true;
    },
    logOut(state) {
      state.isLogged = false;
    },
    saveInRecentGames(state, action) {
      const users = [...state.users];
      const user = users.find((user) => user.id === action.payload.id);
      if (user) {
        const prevState: any = [...user.recentGames];
        user.recentGames.push(prevState, ...action.payload.games);
      }
    },
  },
});

const UserActions = userSlice.actions;
export { userSlice, UserActions };

购物车切片

import { createSlice } from "@reduxjs/toolkit";
import { Cart } from "../types/cart";


const initialState: Cart = {
 game: [],
 totalPrice: 0,
};

const cartSlice = createSlice({
 name: "cart",
 initialState,
 reducers: {
   addToCart(state, action) {
     const newBet = action.payload
     state.game.push(newBet)
     state.totalPrice = state.totalPrice + newBet.price
   },
 },
})
const CartActions = cartSlice.actions
export { cartSlice, CartActions }

【问题讨论】:

    标签: javascript node.js reactjs typescript redux


    【解决方案1】:

    您选择带有“s”的状态games,但是当我查看您的切片时,它的名称不带“s”。

    const { games } = useSelector((state: any) =&gt; state.cart)

    const initialState: Cart = { game: [], totalPrice: 0, };

    【讨论】:

    • 天啊!!我太盲目了。非常感谢你♥
    • Np :) 很高兴我能帮上忙
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多