我有一个名为useFetchMyApi
的自定义hook,它封装了对API端点的fetch请求。该函数钩子接受一个参数并包含在post请求体中。数据数组输出取决于钩子参数。
在UI上,App组件一次调用useFetchMyApi
。按钮点击处理程序将调用后续的useFetchMyApi
来更新UI上的列表。
我的问题:
- 我无法在事件处理程序中调用
useFetchMyApi
,因为这违反了hook的规则。 - 如何刷新基于
useFetchMyApi
响应的项目列表?
import React, { useState, useEffect, useRef } from "react";
import "./styles.css";
const useFetchMyApi = (location = "") => {
const [items, setItems] = useState([]);
useEffect(() => {
// let's stimulate the API call with a 2 seconds response time
setTimeout(() => setItems([location, Math.random()]), 5000);
}, [location]);
return { items };
};
export default function App() {
const locationSelect = useRef(null);
const { items } = useFetchMyApi("mylocation1");
const onButtonClicked = (event) => {
const selectedLocation = locationSelect.current.value;
// Call api and refresh items by location
// Fix here??
//useFetchMyApi(selectedLocation);
};
return (
<div className="App">
<select ref={locationSelect}>
<option value="location1">Location 1</option>
<option value="location2">Location 2</option>
</select>
<button onClick={onButtonClicked}>Refresh</button>
<ul>
{items.map((item) => (
<li>{item}</li>
))}
</ul>
</div>
);
}
https://codesandbox.io/s/stupefied-water-1o6mz?file=/src/App.js:0-1055