React - componentWillReceiveProps中的setState

时间:2015-08-06 15:08:52

标签: javascript reactjs

这合法吗?

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。

有什么建议吗?

4 个答案:

答案 0 :(得分:36)

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

您也可以考虑将此代码放在getInitialState方法中,因为another react doc根据道具初始化不是反模式。

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

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

答案 1 :(得分:3)

从React v16.6.3开始,这被视为UNSAFE和componentWillReceiveProps is marked for deprecation。计划在版本17中进行删除。

  

注意:

     

使用这种生命周期方法通常会导致错误和不一致,因此将来将不推荐使用它。

     

如果您需要因道具更改而产生副作用(例如,数据获取或动画),请改用componentDidUpdate生命周期。

     

对于其他用例,请遵循此博客文章中有关派生状态的建议。

     

如果仅当prop更改时才使用componentWillReceiveProps重新计算某些数据,请改用备忘录助手。

     

如果您在prop更改时使用componentWillReceiveProps来“重置”某些状态,请考虑使用键使组件完全受控或完全不受控制。

     

在极少数情况下,您可能希望将getDerivedStateFromProps生命周期用作最后的选择。

根据您的情况,您应该改用componentDidUpdate

答案 2 :(得分:1)

根据此react doc,不建议更改 componentWillReceiveProps 内部的状态。该文档对此进行了非常清晰的解释。

它也为我们提供了“完全受控的组件”和“不受控制的组件”的替代解决方案,请阅读此react doc

答案 3 :(得分:0)

存在componentWillReceiveProps的唯一原因是使组件有机会进入setState。因此,是的,您在其中同步设置的任何状态都将与新的道具一起处理。

相关问题