[英]Errors while creating a Single Context Provider in React TypeScript
I am trying to create a context for Cart by following this: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js for a React TypeScript project.我正在尝试通过以下方式为购物车创建上下文: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js用于 React TypeScript 项目。
I am confused of what does this Context take in as parameters.我对这个 Context 将什么作为参数感到困惑。 I am getting errors a multiple places.我在多个地方遇到错误。 This is what I have written so far:这是我到目前为止所写的:
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;
These are the errors I am facing:这些是我面临的错误:
// 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)
In order to fix this, I have tried following approaches:为了解决这个问题,我尝试了以下方法:
// 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.
My question here is: Are my two approaches valid?我的问题是:我的两种方法有效吗? Will they be consistent through out and how do I correctly use the Context for types(interface)它们会始终保持一致吗?我如何正确使用类型(接口)的上下文
1 - React.createContext
argument is default value. 1 - React.createContext
参数是默认值。 It's used only when you get context value without provider.仅当您在没有提供者的情况下获得上下文值时才使用它。 If there is no reasonable defaults, you might want to throw error in this case.如果没有合理的默认值,您可能希望在这种情况下抛出错误。 I use null
as default value and custom wrapper arround React.useContext
which throws an error if this would happen.我使用null
作为默认值,并使用自定义包装器React.useContext
如果发生这种情况会引发错误。 https://reactjs.org/docs/context.html#reactcreatecontext https://reactjs.org/docs/context.html#reactcreatecontext
2 - Typescript doesn't know that localStorage.getItem('cart')
always returns the same value in this case, so when it's called the second time, typescript still thinks it might be null. 2 - Typescript 不知道localStorage.getItem('cart')
在这种情况下总是返回相同的值,所以当它被第二次调用时,typescript 仍然认为它可能是 Z37A6259CC0C1DAE299Z0D786 So you should save it to a variable first:所以你应该先把它保存到一个变量中:
const cartString = localStorage.getItem('cart');
const storage = cartString ? JSON.parse(cartString) : [];
or或者
const storage = JSON.parse(localStorage.getItem('cart') ?? "[]");
3 - Typescript have no idea what is payload, so you should specify it manually. 3 - Typescript 不知道什么是有效载荷,因此您应该手动指定它。 Alternatively you can try to use some typescript friendly library to do it ie https://github.com/piotrwitek/typesafe-actions#action-helpers或者,您可以尝试使用一些 typescript 友好库来做到这一点,即https://github.com/piotrwitek/typesafe-actions#action-helpers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.