【发布时间】:2020-02-20 02:31:24
【问题描述】:
我正在尝试使用钩子请求API request。但我的问题是我的函数在我onPress 之前被调用。
我有一个这样的自定义 API 组件:
const FetchDataPut = (URL) => {
useEffect(() => {
async function fetchData() {
const res = await axios({
method: 'put',
url: URL,
data:{
name:'111',
email:'222',
password:'333',
id:'444',
phone:'555'
}
});
const response = await res;
console.log(response, 'completed')
}
fetchData()
},[])
return null
}
我可以从console.log 看到,api 请求有completed。我的问题是我的api component 在我按下按钮之前被调用。
这是我的 Button 组件:
const EditAccount = (props) => {
const Desktop = () => {
const URL = `MyURL...`
return (
<View>
<Button title='edit account' onPress={FetchDataPut(URL)}/>
</View>
)
}
return(
<div>
<Desktop/>
</div>
)
}
如果我将 onPress 函数更改为如下箭头函数:
onPress={()=>FetchDataPut(URL)} 组件在我 onPress 之前没有被调用。但它会给我一个错误Invalid hook call. Hooks can only be called inside of the body of a function component
当我 onPress Button 时,知道如何处理我的 api 请求吗?
任何 cmets 或建议都会非常有帮助。提前致谢! :)
【问题讨论】:
标签: reactjs react-native react-hooks