在React TypeScript中创建单个上下文提供程序时出错



我正试图通过以下操作为Cart创建一个上下文:https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js用于React TypeScript项目。

我很困惑这个上下文将什么作为参数。我在很多地方都犯了错误。这是我迄今为止所写的:

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.

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

1-React.createContext参数是默认值。只有当您在没有提供程序的情况下获得上下文值时,才会使用它。若并没有合理的默认值,在这种情况下,您可能希望抛出错误。我使用null作为默认值,自定义包装器绕过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-助手

最新更新