Reactjs 仅在调用第一个函数后调用第二个函数-react native

Reactjs 仅在调用第一个函数后调用第二个函数-react native,reactjs,react-native,Reactjs,React Native,我刚从react native开始,我从API中提取数据。第一个函数成功调用数据,第二个函数需要第一个函数中的变量才能成功调用。我试图使第二个API调用成功,但失败了 componentDidMount = async () => { const communities = await API.getUserCommunityInfo(userId); console.log(communities) this.setState({userCommunities: communities,

我刚从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
,然后才能进行成功调用

您可以检查第一个函数的响应是否成功,如果成功,然后调用第二个函数

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

只需在第二个函数中添加属性,或者在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})
}

您没有正确地传递回调。通过将回调传递给
.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})
}

setState是异步的,当使用sceond函数时,状态可能没有设置。您不需要传递
this.state.communityMemberId
它处于状态,可以从
this.getGroups()
访问它,而无需将其作为参数传递。我的示例将communityMemberId作为参数传递给getGroup函数。我更喜欢此.getGroups(社区[0].member.id);因为它更快,而且用户不必等待这个.setState方法完成。