Faced Object文字只能在React Typescript中指定已知属性



我在React Typescript中创建项目,并决定使用Hooks+useContext+useReducer。然后,我创建了一个单独的文件来配置初始状态和提供者。但是我面临着使用ADD_TRANSACTIONS的错误。这是我现在的代码:

import * as React from "react";
import { createContext, useReducer, ReactNode } from "react";
import transactionReducer from "./transactionReducer";
const initialState = {
transactions: [
{ id: 1, text: "Cash", amount: 10000 },
{ id: 2, text: "Food", amount: -10000 },
],
};
export const Context = createContext(initialState);
interface Props {
children: ReactNode;
}
const GlobalProvider = ({ children }: Props) => {
const [state, dispatch] = useReducer(transactionReducer, initialState);
const ADD_TRANSACTIONS = (transaction: any) => {
dispatch({ type: "ADD_TRANSACTIONS", payload: transaction });
};
return (
<Context.Provider
value={{
transactions: state.transactions,
ADD_TRANSACTIONS, Here I face the error which is defined below
}}
>
{children}
</Context.Provider>
);
};
export default GlobalProvider;

这是一个错误:

'{ transactions: any; ADD_TRANSACTIONS: (transaction: any) => void; }' is not assignable to type '{ transactions: { id: number; text: string; amount: number; }[]; }'.
Object literal may only specify known properties, and 'ADD_TRANSACTIONS' does not exist in type '{ transactions: {
id: number; text: string; amount: number; }[]; }'.

您这样做是为了使上下文值(提供给组件的内容(与reducer初始状态相同。这些是不同的东西,因为ADD_TRANSACTIONS应该存在于上下文中,而不应该存在于状态中。以下是我建议尝试的:

import * as React from "react";
import { createContext, useReducer, ReactNode } from "react";
import transactionReducer from "./transactionReducer";
interface Transaction {
id: number;
text: string;
amount: number;
}
interface State {
transactions: Transaction;
}
interface GlobalContextType {
addTransaction(transaction: Transaction): void;
state: State;
}
const initialState: State = {
transactions: [
{ id: 1, text: "Cash", amount: 10000 },
{ id: 2, text: "Food", amount: -10000 },
],
};
// Create context with no default value since it will be provided in the component.
// You could try to provide a default value, but it will never be fully complete
// with working functions and everything so I don't see the point in trying.
export const Context = createContext<GlobalContextType>(undefined as any);
// If you don't have any props, get rid of this and replace React.FC<Props>
// later with just React.FC
interface Props {
}
const GlobalProvider: React.FC<Props> = ({ children }) => {
const [state, dispatch] = useReducer(transactionReducer, initialState);
return (
<Context.Provider
value={{
state,
addTransaction(transaction) {
dispatch({ type: "ADD_TRANSACTIONS", payload: transaction });
}
}}
>
{children}
</Context.Provider>
);
};
export default GlobalProvider;

最新更新