javascript - 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>
}
解决方案
与其在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 中的状态。
推荐阅读
- upload - Watson Assistant 上传文件
- asp.net - 反序列化嵌套的 JSON 和 VB.Net (Postmark Json)
- concurrency - 如何同时启动 2 个 CUDA 内核?
- c# - 如何修复错误“请求过滤模块配置为拒绝查询字符串过长的请求”
- r - 在带有正则表达式的 data.table 中使用 %in%
- watchos - WatchOS 6.2.6 - 无法使用独立应用测试 sanbox 应用内购买
- branch - 有人使用anylogic 与Branch 合作吗?
- flutter - 颤振:如何制作自定义颤振容器?
- javascript - 我无法使用 Id 选择元素?
- javascript - 水平折叠仅扩展 1 个元素而不是所有元素