State problem in react WillReceiveProps

class IssueRecordUpload extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
          filters: {},
        }
        
    }
    static propTypes = {
        filters: PropTypes.object,
        dispatch: PropTypes.func
    }
    
      componentDidMount() {
        const {filters} = this.props
        this.setState({
          filters: filters
        }, () => {
          this.load()
        })
      }
      
      componentWillReceiveProps(next) {
        const {filters} = this.state   // filters = undefined
        if (filters.toString() !== next.filters.toString()) {
          this.setState({
            filters: next.filters,
          }, () => {
            this.load()
          })
        }
      }
      
       load = () => {
        const {dispatch} = this.props
        const {filters} = this.state
        dispatch(filters)
      }

}

filters and dispatch are passed in from the parent component. When DidMount, setState () props.filter-> state.filters, receives a new props, in WillReceiveProps and finds that the original state.filters is undefined, and setState fails, but next.filters exists. Solve the reason. Thank you, boss!

May.15,2021

first question:

from the point of view of your current code, the problem should be in componentDidMount .
because this.state.filters in constructor is an empty object, but when passing componentDidMount , it becomes undefined when you take a value in componentWillReceiveProps , then it is likely that when you execute this.setState ({filters: filters}) in componentDidMount , the filters variable, that is, the value of this.props.filters is < code.

put forward some personal opinions for reference:

  • Why take a value from this.props and assign it to this.state when componentDidMount ? in my opinion, this step can be done in constructor .
  • load method as far as your current code is concerned, it should not be placed on your IssueRecordUpload component, but should be dealt with in the parent component, and the processed filters should be given to IssueRecordUpload .

if everything is as you say it is, then one of the things you don't check is whether the props.filters in componentDidMount has a value, and if the parent component initially passes filters is undefined , then everything is fine.

Menu