Ошибка при обновлении объекта состояния в getDerivedStateFromProps () в реакции js - PullRequest
0 голосов
/ 27 апреля 2020

Привет, у меня есть код ниже, где я вызываю API в componentDidMount () и обновляю объект в состояние в методе 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);
...