开发者问题收集

传递给子组件的属性未定义

2018-04-05
50

我有一个父类组件,我正在其中设置本地集,如下所示:

constructor(props) {
    super(props);
    this.state = {
      toogleForms: props.perioder.map((periode, index) => ({ index, open: !periode.bekreftet })),
    };

    this.removePeriodCallback = this.removePeriodCallback.bind(this);
  }

由于在初始渲染时,我没有从 props 获取 perioder ,因此我使用 componentWillReceiveProps 来更新本地状态:

componentWillReceiveProps(props) {
    const toogleFormsLength = this.state.toogleForms.length;

    if (toogleFormsLength < props.perioder.length) {
      const addedPeriod = props.perioder
        .filter((periode, index) => index >= toogleFormsLength)
        .map((periode, index) => ({ index: toogleFormsLength + index, open: !periode.bekreftet }));

      this.setState({ toogleForms: this.state.toogleForms.concat(addedPeriod) });
    }

    if (toogleFormsLength > props.perioder.length) {
      const toogleForms = this.state.toogleForms.filter((periode, index) => index < toogleFormsLength - 1);

      this.setState({ toogleForms });
    }
  }

然后,我将 toogleForms 从本地状态发送到 redux-form fieldArray 组件,如下所示:

  <FieldArray
      name="perioder"
      component={UttakPeriode}
      removePeriodCallback={this.removePeriodCallback}
      inntektsmelding={inntektsmelding}
      toogleForms={this.state.toogleForms}
      toggleFormCallback={this.toggleFormCallback}
    />

但是,在接收此 props 的 UttakPeriode 组件中,当我尝试使用它时,我得到了 undefined

export const UttakPeriode = ({
  fields, inntektsmelding, removePeriodCallback, toggleFormCallback, toogleForms,
}) => (
  <div>
    {fields.map((fieldId, index) => {
      const tilDato = fields.get(index).tom;
      const fraDato = fields.get(index).fom;
      const { uttakPeriodeType, bekreftet, utsettelseÅrsak } = fields.get(index);
      const arbeidsgiverNavn = inntektsmelding[0].arbeidsgiver;
      const showForm = toogleForms.filter(el => el.index === index)[0].open;

这是错误:

TypeError: Cannot read property 'open' of undefined in UttakPeriode (created by ConnectedFieldArray)

我不确定,但我猜子组件在收到 props 之前就被渲染了,所以它未定义。但是,我该如何解决这个问题?

2个回答

您要求同时存在多个状态并可用。我只需将 UttakPeriode 函数中的最后一行拆分为 2 个部分,然后在尝试使用 open 属性之前检查是否有可用数据。

替换:

const showForm = toogleForms.filter(el => el.index === index)[0].open;

替换为:

const form = toogleForms.filter(el => el.index === index)[0];
const showForm = (form) ? form.open : null;
// ...error handle or return if showForm == null
ReyHaynes
2018-04-05

toogleForms 不是 undefined ,因为您可以对其进行过滤,因此在过滤 toogleForms 后,您只会得到空数组。

首先尝试 console.log(toogleForms.filter(el => el.index === index)) 以查看它是否有任何元素。

Artem Mirchenko
2018-04-05