"数据没有发生变化的时候,直接不做处理" 的疑问

来源:8-12 编辑商品页面的开发

ywang04

2018-04-30

   componentWillReceiveProps(nextProps) {
    console.log('this.props is:', this.props)
    console.log('nextProps is:', nextProps)
    let categoryIdChange = this.props.categoryId !== nextProps.categoryId,
      parentCategoryIdChange = this.props.parentCategoryId !== nextProps.parentCategoryId
    // 数据没有发生变化的时候,直接不做处理
    if (!categoryIdChange && !parentCategoryIdChange) {
      console.log('数据不做处理')
      return
    }
    // 假如只有一级品类
    if (nextProps.parentCategoryId === 0) {
      this.setState({
        firstCategoryId: nextProps.categoryId,
        secondCategoryId: 0
      })
    }
    // 有两级品类
    else {
      this.setState({
        firstCategoryId: nextProps.parentCategoryId,
        secondCategoryId: nextProps.categoryId
      },
      () => {
        parentCategoryIdChange && this.loadSecondCategory()
      }
    )
    }
  }

运行场景是: 某商品有一级和二级品类,当第一次点编辑按钮进入到该商品编辑页面的时候 通过console.log打印出如下信息

//img.mukewang.com/szimg/5ae6f8700001aad212520252.jpg

发现"数据没有发生变化的时候,直接不做处理"这段代码运行了。我的问题是为什么调用了loadSecondCategory后 componentWillReceiveProps 又被执行了一次? 这种行为对吗? 而我的环境按照老师的代码写下来 同样的场景 在loadSecondCategory调用后 却不会第二次调用componentWillReceiveProps。

麻烦老师解答下,谢谢!

写回答

1回答

Rosen

2018-05-01

只要父组件有变化的时候,子组建的componentWillReceiveProps就会被调用,这是react的设计。

如果你loadSecondCategory没有触发父组件的变化,就不会有componentWillReceiveProps的调用

0
2
Rosen
回复
ywang04
对的,可以写个demo试下就知道了
2018-05-01
共2条回复

React16+React-Router4 打造企业级电商后台管理系统

【毕设面试】让缺乏框架开发经验的你掌握框架开发

976 学习 · 405 问题

查看课程