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
进行比较
网友评论