react通过props更改state

今天踩了一个坑,ajax请求的数据在props上,在render上可以获取到reducer穿过来的props。但是,render阶段不允许纯函数修改state,在其他阶段(componentdidmount)又获取不到更新的props。

解决办法:

static getDerivedStateFromProps(nextProps, prevState) {
     // 没错,这是一个static
     console.log(nextProps, prevState)
     const { data } = nextProps.headerNavMsg
     return Boolean(data.rmind)
     ?
     {
         ...prevState,
         shortMsgCount: data.shortMsg.length,
         remindCount: data.rmind.length,
         warnCount: data.warn.length
     }
     :
     null
 }

return null表示步修改state

猜你喜欢

转载自blog.csdn.net/weixin_34377065/article/details/90892620