getDerivedStateFromProps没有返回新状态

时间:2020-08-03 11:34:52

标签: react-native getderivedstatefromprops componentwillreceiveprops

我有componentWillReceiveProps,它返回如下所示的更新状态

  componentWillReceiveProps(nextprops) {
    let childDateTime = nextprops.selectedDate != null && nextprops.selectedDate != '' ? nextprops.selectedDate : null;
    let date = nextprops.selectedDate != null && nextprops.selectedDate != '' ? new Date(nextprops.selectedDate) : new Date();

    this.setState({ date, childDateTime });
}

我想用下面的getDerivedStateFromProps代替

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.selectedDate !== prevState.selectedDate) {
        return ({ 
            childDateTime : nextProps.selectedDate != null && nextProps.selectedDate != '' ? nextProps.selectedDate : null,
            date : nextProps.selectedDate != null && nextProps.selectedDate != '' ? new Date(nextProps.selectedDate) : new Date()
        })
    }

    return null;
}

但这不会返回更新状态。我可以知道这段代码有什么问题吗? 谢谢。

0 个答案:

没有答案