简体   繁体   English

为什么当没有从提供者传递任何值时,react-context 返回 undefined,而不是返回默认值?

[英]why react-context is returning undefined when no value has been passed from provider, rather than returning a default value?

I have created react context object with a default value like that:我创建了反应上下文 object ,默认值如下:

const Mycontext = React.createContext("green");

and expected when no value passed to Proivder并在没有值传递给Proivder时预期

the Consumer will get the defualt value I passesed it but rather than it return undefined Consumer获得我传递给它的默认值,但它不会返回undefined的值

please take a look at this simple example on sandbox and tell me what is my wrong请看一下沙盒上的这个简单示例并告诉我我的错误

The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. defaultValue 参数仅在组件在树中的上方没有匹配的 Provider 时使用。

Found in paragraph 2 here https://reactjs.org/docs/context.html#reactcreatecontext在此处的第 2 段中找到https://reactjs.org/docs/context.html#reactcreatecontext

Since you have a provider, regardless of the provider having a value or not, the context won't use the default.由于您有一个提供者,无论提供者是否有值,上下文都不会使用默认值。 If the context can't find a provider, it'll fallback to the default.如果上下文找不到提供者,它将回退到默认值。

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

Check it out here https://codesandbox.io/s/condescending-taussig-6n7tq .在这里查看https://codesandbox.io/s/condescending-taussig-6n7tq

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

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