gpt4 book ai didi

reactjs - createContext 不接受 defaultValue

转载 作者:行者123 更新时间:2023-12-03 23:05:10 27 4
gpt4 key购买 nike

我正在尝试使用 createContext 构建上下文来自 react API:

import React, { useState, createContext } from 'react';

export const MovieContext = createContext();

export const MovieProvider = (props) => {
const [movies, setMovies] = useState(
[
{
original_title: 'name of movie',
poster_path: 'path_to_poster',
id: 1
}
]
);
return (
<MovieContext.Provider value={[movies, setMovies]}>
{props.children}
</MovieContext.Provider>
);
}

export default MovieProvider;
createContext()函数显示此错误:

Expected 1 arguments, but got 0.ts(2554) index.d.ts(385, 9): An argument for 'defaultValue' was not provided.


如果我将其设为字符串,并将字符串作为应用程序构建的值传递:
export const MovieContext =  createContext('');

<MovieContext.Provider value={''}>
{props.children}
</MovieContext.Provider>
我添加什么样的值作为 createContext()参数使其与 useState Hook ?我关注 this guys tutorial他在 JS 中执行此操作,但我在 TS 中构建我的应用程序,所以它更严格一些。

最佳答案

这些是 Typescript 类型,它们被描述为 here .代码中有一条注释为什么需要这个参数,尽管 documentation没有说它是必需的。

function createContext<T>(
// If you thought this should be optional, see
// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/24509#issuecomment-382213106
defaultValue: T,
): Context<T>;
在您的情况下,将正确设置默认参数,例如
type IMovie = {
original_title: string;
poster_path: string;
id: number;
};

type IMovieContext = [IMovie[], React.Dispatch<React.SetStateAction<IMovie[]>>];

export const MovieContext = createContext<IMovieContext>([[], () => null]);

export const MovieProvider = props => {
const [movies, setMovies] = useState<IMovie[]>([
{
original_title: 'name of movie',
poster_path: 'path_to_poster',
id: 1,
},
]);
return <MovieContext.Provider value={[movies, setMovies]}>{props.children}</MovieContext.Provider>;
};

关于reactjs - createContext 不接受 defaultValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63193891/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com