【发布时间】:2020-08-31 13:08:35
【问题描述】:
我正在尝试在应用程序中同时实现 Typescript 和 Context API。我面临着将deleteMovie和addMovie的功能实现到MovieContext.Provider的value prop中的问题。
这是我收到的错误:
Type '{ movies: MovieAttribute[]; deleteMovie: (id: number) => void; addMovie: (id: number, title: string) => void; }' is not assignable to type '{ movies: { id: number; title: string; }[]; }'.
Object literal may only specify known properties, and 'deleteMovie' does not exist in type '{ movies: { id: number; title: string; }[]; }'.ts(2322)
index.d.ts(337, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<{ movies: { id: number; title: string; }[]; }>'
根据我对错误的理解,我是否正确地说我尚未声明我的 Provider 的值不包含“函数类型”。如果是这样,我该如何修改这个问题?
MovieContext.tsx
import React, { createContext, useReducer } from 'react';
import MovieReducer from '../reducers/MovieReducer';
const initialState = {
movies: [
{
id: 1,
title: "King Kong"
},
{
id: 2,
title: "Spiderman"
}
]
};
export const MovieContext = createContext(initialState);
export const MovieProvider = (props: { children: React.ReactNode }) => {
const [state, dispatch] = useReducer(MovieReducer, initialState);
// Actions
function deleteMovie(id: number): void {
dispatch({
type: 'DELETE_MOVIE',
payload: { id, title: 'nil' }
})
}
function addMovie(id: number, title: string): void {
dispatch({
type: 'ADD_MOVIE',
payload: { id, title }
})
}
return (
<MovieContext.Provider value={{
movies: state.movies,
deleteMovie,
addMovie
}}>
{props.children}
</MovieContext.Provider>
)
}
如果代码的任何部分也可以改进,请告诉我!我最近才开始研究 Typescript,而今天刚刚开始研究 Context。
【问题讨论】:
标签: reactjs typescript react-hooks react-context