reactjs 很难为我的本地存储创建正确的类型

uinbv5nw  于 2023-03-08  发布在  React
关注(0)|答案(1)|浏览(116)

我试图编译一个代码,我刚刚用reactJS和TS.但我不能这样做,我可以添加我的本地存储要求正确的类型.我不知道它可能是什么.它只是显示这个错误消息:

  • '变量本地存储:类型为“string”的存储参数|“null”不能赋值给类型“string”的参数。类型“null”不能赋值给类型“string”。“*

下面是完整的代码:

import {
  createContext,
  useState,
  Dispatch,
  SetStateAction,
  ReactNode,
} from 'react';
import { toast } from 'react-hot-toast';
import { Api } from '../../services/Api';

interface ICartContext {
  cartModalState: boolean;
  setCartModalState: Dispatch<SetStateAction<boolean>>;
  foodsToRender: IFoodItem[];
  foodToAddInCart: (uuid: number | string) => void;
  foodsInCart: IFoodItem[];
  setFoodsInCart: Dispatch<SetStateAction<IFoodItem[]>>;
  removeFoodInCart: (number: number) => void;
  getItems: (searchValue?: string) => Promise<void>;
  sumAllValues: () => number;
}

export interface IFoodItem {
  name?: string | any;
  category?: string | any | undefined;
  price?: number;
  img?: string;
  id?: any;
  type?: string;
}

export const CartContext = createContext<ICartContext>({} as ICartContext);

export const CartProvider = ({ children }: { children: ReactNode }) => {
  const [cartModalState, setCartModalState] = useState<boolean>(false);
  const [foodsToRender, setFoodsToRender] = useState<IFoodItem[]>([]);

  const getToken = (): string | false => {
    const getData = JSON.parse(localStorage.getItem('@tokenAndID')) || null;
    if (getData != null) {
      const { token } = getData;
      return token;
    }
    return false;
  };

  const getItems = async (searchValue?: string): Promise<void> => {
    const token = getToken();

    try {
      const response = await Api.get('/products', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (typeof searchValue === 'undefined') {
        setFoodsToRender(response.data);
      } else {
        const filteredData = response.data.filter(
          (food: IFoodItem) =>
            food.name.toLowerCase().includes(searchValue.toLowerCase()) ||
            food.category.toLowerCase().includes(searchValue.toLowerCase())
        );
        setFoodsToRender(filteredData);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const [foodsInCart, setFoodsInCart] = useState<IFoodItem[]>([]);

  const removeFoodInCart = (number: number): void => {
    const leftFoods = foodsInCart.filter((e) => {
      if (e.id !== number) {
        return e;
      }
    });
    setFoodsInCart(leftFoods);
    toast.success('Item removido com sucesso', {
      position: 'top-right',
      duration: 2000,
    });
  };

  const foodToAddInCart = (uuid: number | string): void => {
    const response = foodsInCart.filter((e) => {
      if (e.id == uuid) {
        return e;
      }
    });

    if (response.length > 0) {
      toast.error('Ítem já está na sacola', {
        position: 'top-right',
        duration: 2000,
      });
    } else {
      const selectedFood = foodsToRender.filter((e) => {
        if (e.id == uuid) {
          return e;
        }
      });

      setFoodsInCart([...foodsInCart, ...selectedFood]);

      toast.success('Ítem adicionado com sucesso', {
        position: 'top-right',
        duration: 2000,
      });
    }
  };

  const sumAllValues = (): number => {
    return foodsInCart.reduce((acc, curr) => {
      return acc + curr.price!;
    }, 0);
  };

  return (
    <CartContext.Provider
      value={{
        cartModalState,
        setCartModalState,
        foodsToRender,
        foodToAddInCart,
        foodsInCart,
        setFoodsInCart,
        removeFoodInCart,
        getItems,
        sumAllValues,
      }}
    >
      {children}
    </CartContext.Provider>
  );
};

我试着把||参数为null,但不起作用。还尝试添加“any”类型,但也不起作用

bihw5rsg

bihw5rsg1#

如果可以确定参数永远不会为空,则可以通过在末尾添加感叹号(!)来告知Typescript

const getData = JSON.parse(localStorage.getItem('@tokenAndID'))!

检查此非空Assert

相关问题