从反应函数组件

时间:2018-02-18 13:36:30

标签: javascript reactjs ecmascript-6

我试图从React 16.2中的无状态功能组件中提取业务逻辑。

这有效:

const Jobs = props => (
  props.entries
    .map(entry => (
      <Job
        entry={entry}
        isInitJobExpanded={
          entry.fields.project['en-US'] &&
          props.initJobExpanded &&
          (entry.fields.project['en-US'] === props.initJobExpanded)}
        key={entry.sys.id}
      />
    )));

当我想要提取isInitJobExpanded时,我已尝试过:

const isInitJobExpandedFunction = ({ entry, props }) => (
  entry.fields.project['en-US'] &&
  props.initJobExpanded &&
  entry.fields.project['en-US'] === props.initJobExpanded
);

const Jobs = props => (
  props
    .map(entry => (
      <Job
        entry={entry}
        isInitJobExpanded={isInitJobExpandedFunction}
        key={entry.sys.id}
      />
    )));

但是,我收到错误消息:

Invalid prop `isInitJobExpanded` of type `function` supplied to `Job`, expected `boolean`.`

我也尝试过:

isInitJobExpanded={this.isInitJobExpandedFunction}

isInitJobExpanded={this.isInitJobExpandedFunction()}

isInitJobExpanded={isInitJobExpandedFunction()}

isInitJobExpanded={() => isInitJobExpandedFunction}

提前致谢。

1 个答案:

答案 0 :(得分:1)

isInitJobExpandedFunction会收到一个对象,该对象必须包含两个字段:entryprops。所以你的代码是:

const isInitJobExpandedFunction = ({ entry, props }) => (
  entry.fields.project['en-US'] &&
  props.initJobExpanded &&
  entry.fields.project['en-US'] === props.initJobExpanded
);

const Jobs = props => (
  props
    .map(entry => (
      <Job
        entry={entry}
        isInitJobExpanded={isInitJobExpandedFunction({entry, props})}
        key={entry.sys.id}
      />
    )));