美文网首页
react新的生命周期函数getDerivedStateFrom

react新的生命周期函数getDerivedStateFrom

作者: BlinglingSam | 来源:发表于2019-09-29 15:13 被阅读0次

getDerivedStateFromProps

getDerivedStateFromProps作用是为了让 props 能更新到组件内部 state中。他会在render方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容。但注意在没有内容更新的情况下也一定要返回一个null值。不然会报错。

这个生命周期的意思就是从props中获取state,这个生命周期替换了原有的生命周期函数componentWillReceiveProps,getDerivedStateFromProps,它
是一个静态函数,也就是说不能通过this来访问class的属性,也不推荐直接访问属性。而是通过参数提供的nextPros以及prevState来进行判断,根据新传入的props来映射state
注意:如果传入的props不影响state,则必须返回一个null,一般尽量写在末尾。

static getDerivedStateFromProps(nextProps,prevState){

    // state无更新时return null
    return null;
}

在使用此生命周期时,要注意把传入的 props 值和之前传入的 props 进行比较

相关文章

网友评论

      本文标题:react新的生命周期函数getDerivedStateFrom

      本文链接:https://www.haomeiwen.com/subject/vjvfpctx.html