鍍金池/ 問答/HTML/ react WillReceiveProps中state問題

react WillReceiveProps中state問題

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和dispatch是父組件傳進(jìn)來的,DidMount的時(shí)候setState() props.filter -> state.filters,在WillReceiveProps中再接收新的props,發(fā)現(xiàn)原有state.filters為undefined,并且setState失敗,但是next.filters是存在的,求解是什么原因。謝謝大佬!

回答
編輯回答
眼雜

先答題:

就你目前這些代碼來看,問題應(yīng)該在componentDidMount中。
因?yàn)樵?code>constructor中this.state.filters是一個(gè)空對(duì)象,當(dāng)走過componentDidMount后,在componentWillReceiveProps取值時(shí)卻成了undefined,那么很可能是你在componentDidMount執(zhí)行this.setState({ filters: filters })時(shí),filters變量,也就是this.props.filters的值就是undefined。

提幾點(diǎn)個(gè)人看法,可供參考:

  • 為什么要在componentDidMount時(shí)從this.props上取值并賦值給this.state呢,在我看來,這一步完全可以放到constructor中去做。
  • load方法就你目前這些代碼來看,不應(yīng)該放在你的IssueRecordUpload組件上,而應(yīng)該放到父組件中去處理,并將處理好的filters交給IssueRecordUpload就好了。
2017年7月22日 21:07
編輯回答
尐懶貓

如果一切都如你所說所想, 那么你沒有檢驗(yàn)的一件事就是 componentDidMount 中的 props.filters 是否有值, 父組件如果一開始傳遞的 filters 就是 undefined, 那么一切都是那么的正常.

2017年3月3日 07:46