javascript - React HOC 类不返回任何内容

标签 javascript reactjs

我遇到了一个我无法解决的问题。对于一个项目,我们使用 React 使用以下代码(简化)从 JSON 输入生成布局:

function generateComponents(children, params) {
  let comps = [];
  if (!children || children && children.length === 0) {
    return [];
  }

  forEach(children, (comp) => {
      let compName = comp.component;
      let createdComp;
      switch (compName) {
        case 'test1':
          createdComp = TestOne(Object.assign({}, comp, params));
          break;
        case 'test2':
          createdComp = TestTwo(Object.assign({}, comp, params));
          break;
      }
      comps.push(createdComp)
    }
  }
  return comps.length === 1 ? comps[0] : comps;
}

这很好用并且布局生成正确。我们想更进一步,将 createdComp 包装在 Higher Order Component 中。我们通过以下方式实现了这一点:

function generateComponents(children, params) {
  // see above for implementation

  let component;

  if (condition)
    component = testingHOC(createdComp);
  else
    component = createdComp

  comps.push(component);
}

// TestingHOC.js
export function testingHoc(WrappedComponent) {
  console.log('wrapped')
  return class TestingHoc extends Component {
    render() {
      console.log('props TestingHOC', this.props);
      return ( <WrappedComponent { ...this.props} />);
    }
  }
};

这破坏了我们的组件生成。该代码不返回任何内容。唯一被记录的是 console.log('wrapped'),永远不会调用类的渲染函数。我们在这里缺少什么?

编辑: 渲染类的渲染方法:

render() {
    const children = this.state.children;
    const {params} = this.props;
    const arrChildren = isArray(children) ? children : [children];
    let comps = generateComponents(arrChildren, params || {});
    if (isArray(comps)) {
        return (
            <ViewComponent>
                {comps}
            </ViewComponent>
        );
    } else {
        return comps;
    }
}

编辑 2:

Console.log of {comps} with the testingHoc Console.log of <code>{comps}</code> with the testingHoc {comps} 的 Console.log 没有 testingHoc Desired state of children

编辑 3

添加了 ViewComponent 的代码:

import React from 'react';

const ViewComponent = (props) => (
    <div {...props}/>
);

export default ViewComponent;

最佳答案

您面临的问题是因为 React element and a React component. 之间的内在差异

当您不使用 HOC 时,您正在创建一个可以通过第一个 console.log 图像看到的 React 元素。这是 reconciliation 之后的输出发生了。

当您使用 HOC 时,您的 HOC 会返回一个组件,该组件在您的第二个 console.log 图像中显示为 test(props) 函数。

要与您的 HOC 增强组件具有相同的功能,您需要将 generateComponents 函数中的代码更改为

  if (condition){
     let Comp = testingHOC(createdComp);
     component = <Comp/>;
  }

关于javascript - React HOC 类不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47093750/

相关文章:

javascript - 拼接未按我预期的方式工作

javascript - 用于分享文章的书签

javascript - for循环 react

javascript - 需要在 ReactJS 中的 render() 之前执行函数

reactjs - 如何为echarts bar系列中的每个bar应用不同的线性渐变?

javascript - HTML5 canvas javascript 将图像分割为 6x6

javascript - 警告 : No such label 'RESPONSE TIME' for console. timeEnd()

javascript - 使用 Django + react-router 找不到 404 页面

javascript - 重定向后无法访问组件中的 this.props.location

javascript - Node.js 中的 `stream.Transform.unshift()`