更改道具值,并且子组件在启动时中断

时间:2019-03-04 13:29:18

标签: javascript reactjs react-redux

在CountryTabSequence组件上的渲染中,出现此错误:

  

src / components / CountryTabSequence.js:13:22,   无法读取未定义的属性“ forEach”

因为在加载页面时props值是一个空数组...设置props后如何修复它并重新渲染组件?

我尝试在我的Child组件中使用此修复程序,但这是行不通的:

if(sequence) {
    myForeach...
}

父母:SequenceEdit.js

class SequenceEdit extends Component {
    constructor(props) {
        super(props);

        this.props.getOneSequence(this.props.match.params.id);
    }

    render() {
        return (
            <CountryTabSequence sequence={this.props.currentSequence}/>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        currentSequence: state.currentSequence
    };
};

const mapDispatchToProps = (dispatch) => ({
    ...bindActionCreators({
        getOneSequence
    }, dispatch)
});

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(SequenceEdit));

孩子:CountryTabSequence.js

const renderCountryTabSequence = (sequence) => {
    let countryPreview = '<ul class="nav nav-tabs" id="myTab" role="tablist">';

    if(sequence) {
        sequence.buckets.forEach((bucket) => {
            countryPreview += `<li class="nav-item">${bucket.country.code}</li>`;
        });
    }

    countryPreview += '</ul>';

    return countryPreview;
};

const CountryTabSequence = (props) => {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: renderCountryTabSequence(props.sequence)}}></div>
    );
};

export default CountryTabSequence;

3 个答案:

答案 0 :(得分:0)

我建议检查道具(在所有情况下都得到阵列-是否为空):

onst renderCountryTabSequence = (sequence) => {
    let countryPreview = '<ul class="nav nav-tabs" id="myTab" role="tablist">';
    const { buckets = []} = sequence || {};
    if(Array.isArray(buckets)) {
        sequence.buckets.forEach((bucket) => {
            countryPreview += `<li class="nav-item">${bucket.country.code}</li>`;
        });
    }

    countryPreview += '</ul>';

    return countryPreview;
};

答案 1 :(得分:0)

您需要处理子组件中序列的空条件(必需的道具)。

const renderCountryTabSequence = (sequence) => {

  if (!sequence) {
    return <div>Loading ... ( or any loader component )  </div>
  }

  const htmlToReturn = (
    <ul className="nav nav-tabs" id="myTab" role="tablist">
      {sequence.buckets.map(aBucket => (
        <li
          key={aBucket.country.code}
          className="nav-item">
          {aBucket.country.code}
        </li>
      ))}
    </ul>
  )

  return htmlToReturn;
};

答案 2 :(得分:0)

您可以破坏道具并为其分配默认值,如下所示:

const CountryTabSequence = ({ sequence = [] }) => {
        return (
            <div className="content" dangerouslySetInnerHTML={{__html: renderCountryTabSequence(sequence)}}></div>
        );
    };

或者您可以使用defaultProps为道具分配默认值,如下所示:

CountryTabSequence.defaultProps = {
   sequence: [],
}

我还建议使用某种加载标志来向用户显示数据仍在获取或类似的操作中,以确保用户体验不错。