繁体   English   中英

React Native - API 返回的响应状态在子组件中始终未定义

[英]React Native - Response Status Returned By The API Is Always Undefined In The Child Component

下面是我的代码。 我正在从父组件中的子组件调用一个函数,它根据响应状态进行 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>

}

在此处输入图片说明

与其在 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,因为它独立于父组件中的状态。

您可以尝试使 handlePress 也异步等待吗?

const handlePress = async (lookingToPlay) => {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM