繁体   English   中英

如何使用 redux state 更新反应 HOC 组件?

[英]How to update react HOC component with redux state?

下面是 HOC,它也连接到 redux 商店。 WrappedComponent function 在 storedata 更改时未获取 redux state。 这里有什么问题?

export function withCreateHOC<ChildProps>(
  ChildComponent: ComponentType,
  options: WithCreateButtonHOCOptions = {
    title: 'Create',
  },
) {
  function WrappedComponent(props: any) {
    const { createComponent, title } = options;
    const [isOpen, setisOpen] = useState(false);

    function onCreateClick() {
      setisOpen(!isOpen);
      Util.prevDefault(() => setisOpen(isOpen));
    }

    return (
      <div>
        <ChildComponent {...props} />
        <div>
          <Component.Button
            key={'add'}
            big={true}
            round={true}
            primary={true}
            onClick={Util.prevDefault(onCreateClick)}
            className={'float-right'}
            tooltip={title}
          >
            <Component.Icon material={'add'} />
          </Component.Button>
        </div>
        <OpenDrawerWithClose
          open={isOpen}
          title={title}
          setisOpen={setisOpen}
          createComponent={createComponent}
        />
      </div>
    );
  }

  function mapStateToProps(state: any) {
    console.log('HOC mapStateToProps isOpen', state.isOpen);
    return {
      isOpen: state.isOpen,
    };
  }
  // Redux connected;
  return connect(mapStateToProps, {})(WrappedComponent);
}

期望从ReduxStore使用isOpen并在此处使用WrappedComponent进行更新。 这是否应该更改为 class 组件?

上述 HOC 用作:

export const Page = withCreateHOC(
  PageItems,
  {
    createComponent: <SomeOtherComponent />,
    title: 'Create',
  },
);

概述

您不希望isOpen成为 WrappedComponent 中的本地WrappedComponent 这个 HOC 的重点是从您的 redux 商店访问isOpen 请注意,在此代码中,您没有更改 redux state 的值。 您想放弃本地 state,从 redux 访问isOpen ,并dispatch一个操作以更改 redux 中的isOpen

此外,我们必须用实际类型替换其中的一些any

我似乎有点怀疑您传递的是已解析的 JSX 元素而不是可调用组件作为createComponent<SomeOtherComponent />SomeOtherComponent ),但这是正确还是错误取决于您的OpenDrawerWithClose组件中的内容。 我将假设它是正确的,如此处所写。

使用connect在技术上没有任何问题,但是在 HOC 内部使用 HOC 感觉有点奇怪,所以我将使用钩子useSelectoruseDispatch代替。

一步步

我们想创建一个 function ,它接受一个组件ComponentType<ChildProps>和一些选项WithCreateButtonHOCOptions 您正在为options.title提供默认值,因此我们可以将其设为可选。 options.createComponent是可选的还是必需的?

interface WithCreateButtonHOCOptions {
    title: string;
    createComponent: React.ReactNode;
}
function withCreateHOC<ChildProps>(
  ChildComponent: ComponentType<ChildProps>,
  options: Partial<WithCreateButtonHOCOptions>
) {

我们返回一个 function ,它采用相同的道具,但没有isOpentoggleOpen ,如果它们是ChildProps的属性。

return function (props: Omit<ChildProps, 'isOpen' | 'toggleOpen'>) {

我们需要在解构步骤中为options设置默认值,以便只设置一个属性。

const { createComponent, title = 'Create' } = options;

我们从 redux state 访问isOpen

const isOpen = useSelector((state: { isOpen: boolean }) => state.isOpen);

我们创建了一个回调,它向 redux 发送一个动作——你需要在你的 reducer 中处理这个。 我正在调度一个原始动作 object {type: 'TOGGLE_OPEN'} ,但您可以为此创建一个动作创建者 function 。

const dispatch = useDispatch();
const toggleOpen = () => {
    dispatch({type: 'TOGGLE_OPEN'});
}

我们会将这两个值isOpentoggleOpen作为 props 传递给ChildComponent ,以防万一它想使用它们。 但更重要的是,我们可以将它们用作按钮和抽屉组件的点击处理程序。 (注意:看起来抽屉想要一个带有boolean的道具setIsOpen ,所以你可能需要稍微调整一下。如果抽屉只在isOpentrue时显示,那么只需切换就可以了)。

代码

function withCreateHOC<ChildProps>(
    ChildComponent: ComponentType<ChildProps>,
    options: Partial<WithCreateButtonHOCOptions>
) {
    return function (props: Omit<ChildProps, 'isOpen' | 'toggleOpen'>) {
        const { createComponent, title = 'Create' } = options;

        const isOpen = useSelector((state: { isOpen: boolean }) => state.isOpen);

        const dispatch = useDispatch();
        const toggleOpen = () => {
            dispatch({ type: 'TOGGLE_OPEN' });
        }

        return (
            <div>
                <ChildComponent
                    {...props as ChildProps}
                    toggleOpen={toggleOpen}
                    isOpen={isOpen}
                />
                <div>
                    <Component.Button
                        key={'add'}
                        big={true}
                        round={true}
                        primary={true}
                        onClick={toggleOpen}
                        className={'float-right'}
                        tooltip={title}
                    >
                        <Component.Icon material={'add'} />
                    </Component.Button>
                </div>
                <OpenDrawerWithClose
                    open={isOpen}
                    title={title}
                    setisOpen={toggleOpen}
                    createComponent={createComponent}
                />
            </div>
        );
    }
}

这个版本稍微好一点,因为它没有as ChildProps断言。 我不想过于偏离“为什么”,但基本上我们需要坚持如果ChildProps采用isOpentoggleOpen道具,这些道具必须与我们提供的道具具有相同的类型。

interface AddedProps {
    isOpen: boolean;
    toggleOpen: () => void;
}

function withCreateHOC<ChildProps>(
    ChildComponent: ComponentType<Omit<ChildProps, keyof AddedProps> & AddedProps>,
    options: Partial<WithCreateButtonHOCOptions>
) {
    return function (props: Omit<ChildProps, keyof AddedProps>) {
        const { createComponent, title = 'Create' } = options;

        const isOpen = useSelector((state: { isOpen: boolean }) => state.isOpen);

        const dispatch = useDispatch();
        const toggleOpen = () => {
            dispatch({ type: 'TOGGLE_OPEN' });
        }

        return (
            <div>
                <ChildComponent
                    {...props}
                    toggleOpen={toggleOpen}
                    isOpen={isOpen}
                />
                <div>
                    <Component.Button
                        key={'add'}
                        big={true}
                        round={true}
                        primary={true}
                        onClick={toggleOpen}
                        className={'float-right'}
                        tooltip={title}
                    >
                        <Component.Icon material={'add'} />
                    </Component.Button>
                </div>
                <OpenDrawerWithClose
                    open={isOpen}
                    title={title}
                    setisOpen={toggleOpen}
                    createComponent={createComponent}
                />
            </div>
        );
    }
}

游乐场链接

暂无
暂无

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

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