reactjs - 使用 Hooks 时在 onPress 之前调用反应按钮
问题描述
我正在尝试请求API
request
使用钩子。但我的问题是我的函数在 I 之前被调用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
在我按下按钮之前调用了我的。
这是我的按钮组件:
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
任何想法如何我的 api 请求当onPress
我Button
?
任何意见或建议都会非常有帮助。提前致谢!:)
解决方案
我认为要走的路是使用钩子而不是组件:
const useFetchDataPut = () => {
const [url, setUrl] = useState("");
useEffect(() => {
if (!url) return;
async function fetchData() {
const res = await axios({
method: "put",
url,
data: {
name: "111",
email: "222",
password: "333",
id: "444",
phone: "555"
}
});
const response = await res;
console.log(response, "completed");
}
fetchData();
}, [url]);
return setUrl;
};
然后在按下按钮时调用它。也Desktop
应该在EditAccount
组件之外定义。
const Desktop = () => {
const setUrl = useFetchDataPut();
return (
<View>
<Button
title="edit account"
onPress={() => setUrl("https://...")}
/>
</View>
);
};
const EditAccount = props => {
return (
<div>
<Desktop />
</div>
);
};
如果有不清楚的地方,请告诉我。
推荐阅读
- android - html5视频标签显示只有声音的空白屏幕
- c# - asp.net - SelectItemTemplate 不起作用
- php - Symfony 4 中使用注释路由时的后备路由
- php - 使用 curl 访问 Symfony 4 控制器中的 POST 值
- r - R,Elasticsearch:错误:400 - 不同类型的映射器 [a],current_type [date],merged_type [text]
- firebase - 如何为 Firebase 事件参数重用 Google Analytics
- java - 获取 IndexOutOfBoundsException: Index: 1, Size: 1 单击行时
- typescript - 访问 Vue 中的任意插槽
- mongodb - Mongo db 3.6 和区分大小写的字段名称
- php - 如何生成目录和文件的递归列表以及每个目录和文件的超链接?