首页 > 解决方案 > React Native - API 返回的响应状态在子组件中始终未定义

问题描述

下面是我的代码。我正在从父组件中的子组件调用一个函数,该函数根据响应状态进行 API 调用,我想向子组件添加一些行为,但问题是 API 调用返回的状态始终undefined在子组件中,而我可以console.log在父母中看到预期的状态代码。似乎孩子在收到响应之前正在打印状态,但我相信我在必要的地方有 async/await 但我当然可能是错的。

父组件:

  const MemberHomeScreen = () => {

  const [userProfile, setUserProfile] = useState({});

  const handlePress = async lookingToPlay => {
    console.log("Inside Member Home Screen Looking to play", lookingToPlay);
    try {
      const changeMatchStatus = async () => {
      const response = await axios.put('https://c7971702c7e7.ngrok.io/match', {lookingToPlay});
      console.log("Here is the reponse for the update", response.status); // I can see this
      return response.status;
     }
      changeMatchStatus();
    } catch(error) {
      console.log("There has been an error.")
    }
  }
  
  useEffect(() => {
    try {
        const userData = async () => {
        const response = await axios.get('https://c7971702c7e7.ngrok.io/profile');
        setUserProfile(response.data);
      }
      userData();
    } catch(error) {
      console.log("There has been an error.")
    }
    }, [])

  return(
    <View style={styles.container}>
      { userProfile && <UserMatchButton lookingToPlay={userProfile.lookingToPlay} changeMatchStatus={handlePress} /> }
    </View>
  )
}

子组件:

const UserMatchButton = ({lookingToPlay, changeMatchStatus}) => {
const [matchStatus, setMatchStatus] = useState(lookingToPlay);

const handleLocalPress = async () => {
  const status = await changeMatchStatus(!matchStatus);
  console.log("status in child..............." + status); // always undefined

  setMatchStatus(!matchStatus)
  
}

return <TouchableOpacity 
      onPress={() =>  handleLocalPress()}
    >
      <Text h3 style={styles.statusButton} >Play</Text>
      </TouchableOpacity>

}

在此处输入图像描述

标签: javascriptreactjsreact-nativeasync-await

解决方案


与其在handlePress中创建一个函数,不如直接调用API呢?

 const handlePress = async (lookingToPlay) => {
    try {
      const response = await axios.put('https://c7971702c7e7.ngrok.io/match', {lookingToPlay});
      return response.status;
    } catch(error) {
      console.log("There has been an error.")
    }
  }

此外,似乎可以在子组件中调用 API,因为它独立于 Parent 中的状态。


推荐阅读