道具是未定义的,但我可以看到它在控制台记录道具

时间:2018-09-19 18:51:50

标签: reactjs react-native

我是个新手,只有在用户开始向下滚动时,我才会尝试将更多信息加载到记录数组中。问题是新信息出现在数组中,但是如果您尝试调用它,它将返回undefined。我在这里不明白什么?

父组件:

class ComplementSection extends Component {
  constructor(props) {
    super(props)

    this.state = {
      complements: '',
      updatingComplements: false
    }
    this.updateComplementsArray = this.updateComplementsArray.bind(this)
  }


  componentWillMount() {
    let complements = this.props.user.complements
    let groupComplements = this.props.user.groupComplements
    let allComplements = [...complements, ...groupComplements]
    allComplements.sort(function compare(a, b) {
      dateA = new Date(a.created_at)
      dateB = new Date(b.created_at)
      return dateB - dateA
    })
    this.setState({
      complements: allComplements
    })
  }

  updateComplementsArray() {
    this.state.complements.map((complement, index) => {
      let complements = this.state.complements
      if(complement.meeting_id) {
        meetingApiHelper.getMeeting(this.props.currentUser.authToken, complement.meeting_id)
        .then(results => {
          complements[index].meeting = results.data.data;
          this.setState({complements: complements});
        })
        .catch(err => {
          console.log(err.response)
        })
      }
    })
    this.setState({
      updatingComplements: true
    })
  }

  componentDidUpdate() {
    if(this.props.scrolling === true && this.state.updatingComplements === false) {
      this.updateComplementsArray()
    }
  }



  render() {
    if(this.props.scrolling === true && this.state.updatingComplements === true){
      return(
        <View>
            <Text style={profileStyles.yellowLobsterHeader}>Complements</Text>
            <FlatList
              data={this.state.complements}
              renderItem={({item}) => <ComplementItem key={item.id}  item={item} navigation={this.props.navigation}  />}
              keyExtractor={(item, index) => index}
            />
        </View>
      )
    } else {
      return null
    }
  }
}

export default ComplementSection

子组件:

class ComplementItem extends Component {
  constructor(props) {
     super(props)
  }

  componentDidMount() {
    console.log(this.props.item)
    console.log(this.props.item.meeting)
  }

  render() {
    return (
      <View style={formStyles.formStandard}>
          <Text style={profileStyles.profileBio}>Placeholder text</Text>
      </View>
    )
  }
}

export default ComplementItem;

componentDidMount函数中,this.props.item返回:

{created_at:"2017-11-08T22:11:27.272Z"
id:29
meeting:{id: 219, requestor_id: 441, requestee_id: 32, lang_one_id: 1, lang_two_id: 6, …}
meeting_id:219
notes:"Clex Sss was really nice and very easy to talk to. I look forward to meeting again!"
reviewee:32
reviewer:441
updated_at:"2017-11-08T22:11:27.272Z"}

但是this.props.item.meeting返回undefined

我在这里想念什么?

1 个答案:

答案 0 :(得分:3)

这里有两个问题

第一

你不应该改变状态

let complements = this.state.complements
complements[index].meeting = results.data.data; //... Here, you should either use a spread to shallow compare or use tradition JS fix JSON.parse(JSON.stringify(your_obj)) for a deep clone

第二

一旦api获取成功,您就不必在每次地图迭代上更新state ,这可能会导致性能问题。

因此,在这种情况下,您可以使用async/await

updateComplementsArray = async () => {
    const updatedCompliments = await Promise.all(
      this.state.complements.map(async (complement, index) => {
        if(complement.meeting_id) {
          try {
            const meetingResults = await meetingApiHelper.getMeeting(this.props.currentUser.authToken, complement.meeting_id)
            complement.meeting = meetingResults.data.data;
          } catch(ex) {
            // handle the api exception here
          }
        }
        return complement // Map expects a return for each iteration. Return the updated complement object here
      })
    )
    // Once the Promises inside map finish executing, update the state
    this.setState({ complements: updatedCompliments });
  }