美文网首页
componentWillReceiveProps代替方案

componentWillReceiveProps代替方案

作者: Poppy11 | 来源:发表于2020-07-29 15:14 被阅读0次
componentWillReceiveProps 这个周期函数在最新的react 不建议用了,所以官网也给我们推荐了新的用法。
componentWillReceiveProps 是为了解决props是异步获取的时候使自组件正确获得最新props的方法,一般我们只需要用第一个参数,nextProps(即是最新props)就可以满足需求。

官方代替方案是用 getDerivedStateFromProps 来代替 componentWillReceiveProps,下面看看代码,我这里实现的需求就是获取到最新的currentKey,并且获取了后就立即调用回调函数。

   componentWillReceiveProps(nextProps) {
        this.setState({
            currentKey: nextProps.currentKey,
        }, () => {
            let page = Page.GetPage()
            this.getAllProduct(page)
        })
    }

使用getDerivedStateFromProps替代过后
  static getDerivedStateFromProps(nextProps, prevState) {
        //该方法内禁止访问this
        if (nextProps.condition !== prevState.condition) {
            //通过对比nextProps和prevState,返回一个用于更新状态的对象
            return {
                condition: nextProps.condition
            }
        }
        //不需要更新状态,返回null
        return null
    }

 componentDidMount() {
        const {page} = this.props.productPage
        const curentPage = isNaN(page) ? 1 : page
        this.getAllProduct(curentPage)
    }

代替方案是: 是一个静态方法, 需要把props 用 state 存起来,然后 用 preState来获取上一个props,第二,componentWillReceiveProps 直接 setState而 getDerivedStateFromProps 则是return 一个对象就好,它相当于setState,还有一个细节,后面的 return null;

getDerivedStateFromProps 不能直接this.xxx。无解了吗?,当然是由解决办法的,下图:


image.png

相关文章

网友评论

      本文标题:componentWillReceiveProps代替方案

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