【问题标题】:Manage props changes in react native管理 react native 中的 props 更改
【发布时间】:2019-07-11 00:10:40
【问题描述】:

我正在使用 react native 构建约会应用程序,这是我在 RC 中的第一次尝试,使用 react-redux 来管理状态。我需要对生命周期方法进行一些说明。

Details.js

class Details extends Component {
   constructor(props) {
     super(props);
     }

   componentDidMount(){
   this.props.bookingAndSuggestions(Data)
    }

    componentWillReceiveProps(nextProps){
     if( Object.keys(nextProps.bookingSuggestionStatus).length >0) {
      if(nextProps.bookingSuggestionStatus.res.data.status=='available') {
        this.setState({isAvailable:false})
      } else {
        this.setState({isAvailable:true})
      }} }

   onBookNow=()=>{
    this.props.shops(Data);
   }

这是交易,最初我调用 react-redux action prop this.props.bookingAndSuggestions(Data) 并在 componentWillReceiveProps 中捕获响应,预订时 this.props.shops(Data); 将触发,它还会更新 componentWillrecieveprops,内部逻辑每次 props 发生变化时,componentwillrecieveprops 都会更新。处理这种情况的正确方法是什么?

【问题讨论】:

    标签: reactjs react-native react-redux


    【解决方案1】:

    componentWillReceiveProps 不仅会在 props 更改时调用,而且还会在父级重新渲染时调用,因此每当调用它时,都会重新评估和设置状态。

    你有两个选择

    1. 如果您没有在内部修改 isAvailable 状态,您可以直接从 props 中使用它。

    例如:

    const isAvailable = this.props.bookingSuggestionStatus && this.props.bookingSuggestionStatus.res.data.status=='available'
    
    1. 如果你正在修改它,那么你需要检查道具是否发生了变化,你可以在componentWillReceiveProps中进行操作(从v16.3.0开始使用getDerivedStateFromProps

    例如:

    componentWillReceiveProps(nextProps){
         if(!_.isEqual(nextProps.bookingSuggestionStatus, this.props.bookingSuggestionStatus) && Object.keys(nextProps.bookingSuggestionStatus).length >0) {
          if(nextProps.bookingSuggestionStatus.res.data.status=='available') {
            this.setState({isAvailable:false})
          } else {
            this.setState({isAvailable:true})
          }
         } 
    }
    

    【讨论】:

    • 还值得注意的是componentWillReceivePropsdeprecated
    • @Andrew,如果不清楚,我想我应该在答案中明确添加
    猜你喜欢
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 2015-12-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    相关资源
    最近更新 更多