简体   繁体   English

createContext 不接受 defaultValue

[英]createContext doesn't accept defaultValue

I'm trying to build a context by using createContext from the react API:我正在尝试通过使用来自反应 API 的createContext来构建上下文:

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;

The createContext() function shows this error: createContext() function 显示此错误:

Expected 1 arguments, but got 0.ts(2554) index.d.ts(385, 9): An argument for 'defaultValue' was not provided.预期为 1 arguments,但得到 0.ts(2554) index.d.ts(385, 9):未提供“defaultValue”的参数。

If I make it a string, and pass a string as value the app builds:如果我将其设为字符串,并将字符串作为应用程序构建的值传递:

export const MovieContext =  createContext('');

<MovieContext.Provider value={''}>
  {props.children}
</MovieContext.Provider>

What kind of value do I add as a createContext() parameter to make it work with the useState hook?我应该添加什么样的值作为createContext()参数以使其与 useState 挂钩? I'm following this guys tutorial and he does it in JS but I'm building my app in TS so it's a bit more strict.我正在关注这个人的教程,他在 JS 中做,但我在 TS 中构建我的应用程序,所以它更严格一些。

These are the Typescript types, they are described here .这些是 Typescript 类型,它们在此处进行了描述。 There is a comment in the code why this argument should be required, although the documentation doesn't say it is required.代码中有一条注释为什么需要这个参数,尽管文档没有说它是必需的。

function createContext<T>(
    // If you thought this should be optional, see
    // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/24509#issuecomment-382213106
    defaultValue: T,
): Context<T>;

In your case will correctly set the default parameter like在您的情况下,将正确设置默认参数,例如

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>;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM