仅在调用第一个函数后才调用第二个函数-反应本机

时间:2019-06-01 08:52:51

标签: reactjs react-native

我刚开始使用react native,并且正在从API中提取数据。第一个函数成功调用数据,第二个函数需要第一个函数中的变量才能成功调用。我正在尝试使第二个API调用成功,但是失败

componentDidMount = async () => {
const communities = await API.getUserCommunityInfo(userId);
console.log(communities)
this.setState({userCommunities: communities, communityMemberId: communities[0].member.id, communityId: communities[0].community.id}, 
console.log(this.state),
this.getGroups()
)

}

第二功能

getGroups = async () => {
const groups = await API.getGroups(communityMemberId)
this.setState({userGroups: groups ,showLoader: false})
}

第二个函数在成功调用之前将需要第一个函数communityMemberId的状态

3 个答案:

答案 0 :(得分:1)

您没有正确传递回调。通过将回调传递给.setState(),第二个函数将在第一个函数完成设置状态后运行。

componentDidMount = async () => {
  const communities = await API.getUserCommunityInfo(userId);
  console.log(communities);
  this.setState(
    {
      userCommunities: communities,
      communityMemberId: communities[0].member.id,
      communityId: communities[0].community.id
    },
    () => {
      console.log(this.state);
      this.getGroups()
    }
  );
};

getGroups函数

getGroups = async () => {
  const groups = await API.getGroups(this.state.communityMemberId)
  this.setState({userGroups: groups ,showLoader: false})
}

答案 1 :(得分:0)

您可以检查第一个功能是否响应,是否成功,然后调用第二个功能。

getGroups = async () => {
const groups = await API.getGroups(communityMemberId)
this.setState({userGroups: groups ,showLoader: false})
   if(succees){
    //call second function
    this.secondFunction()
   }
}

答案 2 :(得分:0)

只需将一个属性添加到第二个函数中,或在setState完成后添加一个回调函数。

componentDidMount = async () => {
    const communities = await API.getUserCommunityInfo(userId);
    console.log(communities)
    this.setState({
       userCommunities: communities, 
       communityMemberId: communities[0].member.id, 
       communityId: communities[0].community.id
    }, () => {
        this.getGroups(this.state.communityMemberId); // callback function after the state is updated
    });
    // or 
    this.getGroups(communities[0].member.id); // this is faster since user don't wait state to be updated
}

getGroups = async (communityMemberId) => {
    const groups = await API.getGroups(communityMemberId)
    this.setState({userGroups: groups ,showLoader: false})
}