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

时间:2018-04-05 14:47:22

标签: javascript reactjs

我有一个父类组件,我在这里设置本地集:

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

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

因为,在初始渲染时,我不会从perioder props获取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 }); } } 来更新本地状态:

redux-form

然后,我将toogleForms从本地状态发送到fieldArray <FieldArray name="perioder" component={UttakPeriode} removePeriodCallback={this.removePeriodCallback} inntektsmelding={inntektsmelding} toogleForms={this.state.toogleForms} toggleFormCallback={this.toggleFormCallback} /> 组件,如下所示:

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;

SELECT
     CASE WHEN ab.col1='NULL THEN ab.col2  
          ELSE ab.col1 END as col
FROM table1 as ab;

这是错误:

  

TypeError:无法读取属性&#39;打开&#39;在UttakPeriode中未定义   (由ConnectedFieldArray创建)

我不确定,但我想这个子组件在收到道具之前会被渲染,这就是它未定义的原因。但是,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您要求许多州同时到位并且可以使用。我只是将UttakPeriode函数中的最后一行分解为两部分,并在尝试使用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

答案 1 :(得分:0)

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

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