这合法吗?

componentWillReceiveProps: function(nextProps) {
        if (typeof nextProps.contact != 'undefined') {
            this.setState({forename: nextProps.contact.forename});
            this.setState({surname: nextProps.contact.surname});
            this.setState({phone: nextProps.contact.phone});
            this.setState({email: nextProps.contact.email});
        }
    }

因为我不知道如何填写输入内容,但仍然能够使用户编辑输入内容。所以我想出了这个解决方案,而不是试图操纵this.props。

有什么建议?

最佳答案

根据react documentation,您的代码是合法的。

您还可以考虑将此代码放入getInitialState方法中,因为根据another react doc从props初始化不是反模式。

您还可以用一个setState方法调用替换多个调用:

 this.setState({forename: nextProps.contact.forename,
                surname: nextProps.contact.surname,
                phone: nextProps.contact.phone,
                email: nextProps.contact.email});

09-18 19:02