【问题标题】:How to access dispatch method of multiple contexts in React Context API hooks?如何在 React Context API 挂钩中访问多个上下文的调度方法?
【发布时间】:2020-05-04 07:59:24
【问题描述】:

我有一个包含多个上下文的应用:

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

我已经使用 React Context API 建立了类似 Redux 的存储,并在 reducer 中使用了调度方法。我的两个提供商都是这样设置的:

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

现在我需要从一个组件访问两个提供者的调度方法,但是它会抛出一个错误...请看下面的 cmets 代码:

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.

}

我在这里缺少什么?

【问题讨论】:

  • 我知道可能的答案是:将您的组件减少为更小的部分并重新安排您的商店,因此每个组件只需要一个商店。但是,如何在 react 组件中访问两个或多个商店的 dispatch reducer?

标签: reactjs react-context


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

        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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2019-05-28
      • 2020-08-12
      • 2020-04-01
      相关资源
      最近更新 更多