Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么react上下文在没有从提供程序传递任何值时返回undefined,而不是返回默认值?_Javascript_Reactjs - Fatal编程技术网

Javascript 为什么react上下文在没有从提供程序传递任何值时返回undefined,而不是返回默认值?

Javascript 为什么react上下文在没有从提供程序传递任何值时返回undefined,而不是返回默认值?,javascript,reactjs,Javascript,Reactjs,我已经用默认值创建了react上下文对象 就像这样: const Mycontext = React.createContext("green"); 当没有值传递给Proivder时,为预期值 消费者将获得我传递给它的解除值,但不是返回未定义的值 请看一下这个简单的例子,告诉我我的错误是什么 defaultValue参数仅在组件没有 树中位于其上方的匹配提供程序 见此处第2段 由于您有一个提供程序,无论该提供程序是否具有值,上下文都不会使用默认值。如果上下文找不到提供程序,它将返回默认值 co

我已经用默认值创建了react上下文对象 就像这样:

const Mycontext = React.createContext("green");
当没有值传递给Proivder时,为预期值

消费者将获得我传递给它的解除值,但不是返回未定义的值

请看一下这个简单的例子,告诉我我的错误是什么


defaultValue参数仅在组件没有 树中位于其上方的匹配提供程序

见此处第2段

由于您有一个提供程序,无论该提供程序是否具有值,上下文都不会使用默认值。如果上下文找不到提供程序,它将返回默认值

const MyContext = createContext("I'm the default value")

function MyProvider(props) {
  return <MyContext.Provider {...props} />
}

function MyConsumer() {
  return (
    <MyContext.Consumer>{(value) => console.log(value)}</MyContext.Consumer>
  )
}

// Should not use the default from createContext since there is a valid provider.
function AppWithProvider() {
  return (
    <MyProvider>
      <MyConsumer />
    </MyProvider>
  )
}

// Should use the default from createContext since there is no provider.
function AppWithoutProvider() {
  return <MyConsumer />
}
看看这里


defaultValue参数仅在组件没有 树中位于其上方的匹配提供程序

见此处第2段

由于您有一个提供程序,无论该提供程序是否具有值,上下文都不会使用默认值。如果上下文找不到提供程序,它将返回默认值

const MyContext = createContext("I'm the default value")

function MyProvider(props) {
  return <MyContext.Provider {...props} />
}

function MyConsumer() {
  return (
    <MyContext.Consumer>{(value) => console.log(value)}</MyContext.Consumer>
  )
}

// Should not use the default from createContext since there is a valid provider.
function AppWithProvider() {
  return (
    <MyProvider>
      <MyConsumer />
    </MyProvider>
  )
}

// Should use the default from createContext since there is no provider.
function AppWithoutProvider() {
  return <MyConsumer />
}

请在此处查看。

defaultValue参数仅在树中组件上方没有匹配的提供程序时使用。因为您有一个提供者,所以它不会使用默认值。见第二段。@DennisMartinez非常感谢。。。您可以将其添加为应答PLZ吗?defaultValue参数仅在树中组件上方没有匹配的提供程序时使用。因为您有一个提供者,所以它不会使用默认值。见第二段。@DennisMartinez非常感谢。。。你能把它添加为回答plz吗