如何在React Context API钩子中访问多个上下文的调度方法?

时间:2020-01-17 12:17:56

标签: reactjs react-context

我有一个具有多个上下文的应用程序:

class App extends Component {
  render() {
    return (
      <SettingsProvider>
        <ContentProvider>
          <Component />
        </ContentProvider>
      </SettingsProvider>
    );
  }
}

并且我已经使用React Context API以及Reduces中的调度方法建立了类似Redux的商店。我的两个提供商都是这样设置的:

import reducer from './reducers';

export const SettingsContext = createContext();

function SettingsProvider({ children, userSettings }) {
  const [state, dispatch] = useReducer(
    reducer,
    _.merge(defaultSettings, JSON.parse(userSettings)),
  );

  return (
    <SettingsContext.Provider value={{ state, dispatch }}>{children}</SettingsContext.Provider>
  );
}

现在我需要从一个组件访问两个提供程序的调度方法,但是会引发错误...请参见下面带有注释的代码:

function Settings() {
    // This works in most components, which need to access only one context
    const {state, dispatch} = React.useContext(ContentContext);

    // This method works for accessing multiple contxest
    const settings = React.useContext(SettingsContext);   // accessable as settings.state
    const content = React.useContext(ContentContext);     // content.state.

    // but now this is throwing an error that settings and dispatchSettings are undefined..
    const {settings, dispatchSettings} = React.useContext(SettingsContext);   // accessable as settings.state
    const {content, dispatchContent} = React.useContext(ContentContext);     // content.state.

}

我在这里想念的是什么?

2 个答案:

答案 0 :(得分:0)

我相信您应该重命名调度变量。

    function SettingsProvider({ children, userSettings }) {
       const [state, dispatchSettings] = useReducer(
       reducer,
       _.merge(defaultSettings, JSON.parse(userSettings)),
    );

    return (
      <SettingsContext.Provider value={{ state, dispatchSettings }}> 
          {children} 
      </SettingsContext.Provider>
          );

ContentProvider reducer将使用相同的方法。

答案 1 :(得分:0)

您可以将重命名与对象销毁一起使用,例如

const { dispatch } = useContext(DefaultContext);
const { dispatch: altDispatch } = useContext(AltContext);

现在可以使用dispatch访问DefaultContext的调度,而使用altDispatch访问AltContext。