首页 文章

状态不使用上下文api和HOC更新不同的组件

提问于
浏览
0

我正在尝试使用context api更新应用程序的状态,因为我不需要redux的所有功能,我不想处理prop钻孔 . 因此,使用typescript,我创建了一个全局上下文和一个包装组件的HOC包装器,以便组件类可以访问上下文 .

import * as React from 'react';

import GlobalConsumer from './globalConsumer';
import GlobalProvider from './globalProvider';
import IGlobalState from './globalState';

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
type Subtract<T, K> = Omit<T, keyof K>;

export interface IInjectWithState {
  globalState: IGlobalState;
}

const withState = <P extends IInjectWithState>(
  Component: React.ComponentType<P>
): React.ComponentType<Subtract<P, IInjectWithState>> =>
  class WithState extends React.Component<Subtract<P, IInjectWithState>> {
    public render(): JSX.Element {
      return (
        <GlobalProvider>
          <GlobalConsumer>
            {state => <Component {...this.props} globalState={state} />}
          </GlobalConsumer>
        </GlobalProvider>
      );
    }
  };

export default withState;

这是HOC .

import * as React from 'react';

import reducer from './reducer';

import IGlobalState from './globalState';

import GlobalContext, { initState } from './globalContext';

class GlobalProvider extends React.Component<{}, IGlobalState> {
  constructor(props: any) {
    super(props);
    this.state = {
      ...initState,
      dispatch: (action: object) =>
        this.setState(() => {
          return reducer(this.state, action);
        })
    };
  }

  public render(): JSX.Element {
    return (
      <GlobalContext.Provider value={this.state}>
        {this.props.children}
      </GlobalContext.Provider>
    );
  }
}

export default GlobalProvider;

这是提供者 .

大多数类都包含在HOC中,但每当我调用dispatch并更改其中一个组件类中的状态时,全局状态不会在其他组件类中更新 .

RootView.tsx:35 
{appBarTitle: "Welcome", canContinue: true, currentPage: Array(0), dispatch: ƒ, nextPage: Array(0), …}
    ContinueButton.tsx:31 
{appBarTitle: "Welcome", canContinue: true, currentPage: Array(0), dispatch: ƒ, nextPage: Array(0), …}
    RootView.tsx:39 
{appBarTitle: "Welcome", canContinue: true, currentPage: Array(1), dispatch: ƒ, nextPage: Array(1), …}
    Start.tsx:21 
{appBarTitle: "Welcome", canContinue: true, currentPage: Array(0), dispatch: ƒ, nextPage: Array(0), …}
    ContinueButton.tsx:35 
{appBarTitle: "Welcome", canContinue: true, currentPage: Array(0), dispatch: ƒ, nextPage: Array(0), …}

在根视图中调用dispatch后更新组件,但在更新另一个类中的状态后,它不会在其他类中更新 .

1 回答

  • 0

    现在设置它的方式,使用HOC的组件的每个实例都有自己的 GlobalProvider 实例,因此它有自己独立的"global"状态 . 尝试从HOC中删除 GlobalProvider ,而是在组件树的最外层添加单个 GlobalProvider 组件 .

相关问题