Литерал Faced Object может указывать только известные свойства в React Typescript - PullRequest
0 голосов
/ 11 апреля 2020

Я создавал проект в 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; }[]; }'.

1 Ответ

0 голосов
/ 11 апреля 2020

Вы сделали так, чтобы значение вашего контекста (что предоставляется компонентам) было таким же, как и начальное состояние редуктора. Это разные вещи, потому что 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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...