设置上下文 属性 值的函数为空但有效。为什么?

Function which sets context property value is empty but works. Why?

我正在按照 YouTube 上的教程使用 React Context 制作一个非常基础的程序。有一部分让我很困惑,默认上下文中有两个属性:

import React from "react"

const defaultContext = {
    markdownText: "",
    setMarkdownText: () => {},    
}

export default React.createContext(defaultContext)

setMarkdownText 属性 从未真正更新过,仍然是一个空函数。

const {setMarkdownText} = useContext(editorContext)

const onInputChange = e => {
    const newValue = e.currentTarget.value;
    setMarkdownText(newValue)
}

那么 setMarkdownText 如何实际改变 markdownText 属性 尽管在上面的代码中是一个空函数?

A link to the complete project on codesandbox.io

实际值已传递给 App.js 中的上下文提供程序。默认上下文值只是安全机制,以防有人在没有提供者的情况下使用消费者。

这里是相关文档:https://reactjs.org/docs/context.html

解释:

// editorContext.js

// this is our default "fallback" values for context
const defaultContext = {
  markdownText: "",
  setMarkdownText: () => {},
};

// We are creating context instance
export default React.createContext(defaultContext);

// App.js
export default function App() {
  //  this state and state setting fucntion will be our actual context value
  const [markdownText, setMarkdownText] = useState("");
  // we prepare it here
  const contextValue = {
    markdownText,
    // This is our actual `setMarkdownText`
    setMarkdownText,
  };

  // and pass it into EditorContext.Provider as a value prop
  // This value will be used for every consumer inside the tree, instead of default value
  return (
    <EditorContext.Provider value={contextValue}>
      <AppContainer>
        <Title>Markdown Editor</Title>
        <EditorContainer>
          <MarkedInput />
          <Result />
        </EditorContainer>
      </AppContainer>
    </EditorContext.Provider>
  );
}