在React JS中更新getDerivedStateFromProps()中的状态对象时出错

时间:2020-04-27 13:23:42

标签: reactjs react-redux state react-props

嗨,我有下面的代码,我在componentDidMount()中调用一个api,并在getDerivedStateFromProps()方法中将对象更新为状态。但是,当我尝试在render()中读取其值时,出现以下错误。

abd.filter不是函数

下面是我的代码段。

import React, { Component } from "react";
import { connect } from "react-redux";
import * as customerActions from "../actions/CustomerAction";

class Customer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      features: [],
    };
  }

  //fetching user's features for his eligible set of actions
  componentDidMount() {
    this.props.dispatch(customerActions.getFeatures("custName"));
  }

  static getDerivedStateFromProps(props, state) {
	  //1st time no data and 2nd time have a data in state
    return { features: props.features };
  }

  render() {
    const abd = this.state.features;//I have undefined here when component render for the first time and 2nd time I have a data 
    if (abd) {
      const feat = abd.filter((source) => source.FEATURE_CODE === "abc");// error on this line as abd.filter is not a function
      let a = [];
      feat.forEach(function (obj) {
        a.push(obj.FEATURE);
      });
      console.log("a in reder", a);
    }

    return <div>Hi</div>;
  }
}

function mapStateToProps(state) {
  return {
    features: state.features,
  };
}

export default connect(mapStateToProps)(Customer);

0 个答案:

没有答案