【问题标题】:Errors while creating a Single Context Provider in React TypeScript在 React TypeScript 中创建单个上下文提供程序时出错
【发布时间】:2021-05-19 06:30:15
【问题描述】:

我正在尝试按照以下内容为购物车创建上下文:https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js 用于 React TypeScript 项目。

我对这个 Context 将什么作为参数感到困惑。我在多个地方遇到错误。这是我到目前为止所写的:

import React, { createContext, useReducer } from 'react';
import { CartReducer, sumItems } from './CartReducer';

export const CartContext = createContext({}); <-- 1) Ambiguity Here

type Props = { children: React.ReactElement }

const storage = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : []; <-- Error1 here
const initialState = { cartItems: storage, ...sumItems(storage), checkout: false };

const CartContextProvider = ({children} : Props) => {
     const [state, dispatch] = useReducer(CartReducer, initialState)
     const increase = payload => {    <-- Error2 Here and for all Payloads below
          dispatch({ type: 'INCREASE', payload })
     }
     const decrease = payload => {
          dispatch({ type: 'DECREASE', payload })
     }
     const addProduct = payload => {
          dispatch({ type: 'ADD_ITEM', payload })
     }
     const removeProduct = payload => {
          dispatch({ type: 'REMOVE_ITEM', payload })
     }
     const clearCart = () => {
          dispatch({ type: 'CLEAR' })
     }
     const handleCheckout = () => {
          console.log('CHECKOUT', state);
          dispatch({ type: 'CHECKOUT' })
     }
     const contextValues = {
          removeProduct,
          addProduct,
          increase,
          decrease,
          clearCart,
          handleCheckout,
          ...state
     }
     return (
          <CartContext.Provider value={contextValues} >
               { children}
          </CartContext.Provider>
     );
}
export default CartContextProvider;  

这些是我面临的错误:

// Ambiguity Here:
I am not sure if I can pass an empty JSON object, it might be working for now, but Ideally in Typescript we must pass a parameter type. And I am wondering what Parameter(Interface) this context could take.

// Error1:
var localStorage: Storage
Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.ts(2345)

// Error2:
(parameter) payload: any
Parameter 'payload' implicitly has an 'any' type.ts(7006)

为了解决这个问题,我尝试了以下方法:

// Fix for Error1:
const storage = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart') || '{}') : [];

// Fix for Error2:
type PropsforPayload = { payload: React.ReactElement }
const increase = (payload: PropsforPayload) => { //Similar for all the occurences.

我的问题是:我的两种方法是否有效?它们会始终保持一致吗?我如何正确使用类型(接口)的上下文

【问题讨论】:

    标签: javascript reactjs typescript react-context


    【解决方案1】:

    1 - React.createContext 参数是默认值。仅当您在没有提供者的情况下获得上下文值时才使用它。如果没有合理的默认值,您可能希望在这种情况下抛出错误。我使用null 作为默认值和自定义包装器arround React.useContext,如果发生这种情况会引发错误。 https://reactjs.org/docs/context.html#reactcreatecontext

    2 - Typescript 不知道localStorage.getItem('cart') 在这种情况下总是返回相同的值,所以当它被第二次调用时,typescript 仍然认为它可能为 null。所以你应该先把它保存到一个变量中:

    const cartString = localStorage.getItem('cart');
    const storage = cartString  ? JSON.parse(cartString) : [];
    

    const storage = JSON.parse(localStorage.getItem('cart') ?? "[]");
    

    3 - Typescript 不知道什么是有效载荷,因此您应该手动指定它。或者,您可以尝试使用一些对打字稿友好的库来做到这一点,即https://github.com/piotrwitek/typesafe-actions#action-helpers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2019-01-01
      • 2019-07-24
      • 2023-02-13
      • 2022-10-06
      • 2020-12-02
      相关资源
      最近更新 更多