【发布时间】:2020-12-18 19:12:49
【问题描述】:
所以我有一个钩子,我有一个方法可以通过 id 调用统计信息,还有一个方法可以调用可用统计信息列表。
我想首先调用统计列表,然后通过第一个响应中第一个项目的 id 调用实际的统计数据。看起来有点像。像这样:
挂钩
const useMapStatistics = () => {
const [selectedStatistics, setSelectedStatistics] = useState(null); // maybe use a useRef here ?
const [allMapStatistics, setAllMapStatistics] = useState([]);
const [geoJSON, setGeoJSON] = useState({
type: "",
features: [],
});
const fetchMapStatisticsById = useCallback((type) => {
getMapStatisticsById({ type })
.then((result) => setGeoJSON(result));
},
[]
);
const fetchInitialMapStatistics = useCallback(() => {
getMapStatisticsList().then((list) => {
setAllMapStatistics(list.statistics);
setSelectedStatistics(list.statistics[0]);
return list.statistics[0];
})
.then((type) => fetchMapStatisticsById(type));
}, [fetchMapStatisticsById]);
useEffect(() => {
fetchInitialMapStatistics();
}, []);
return {
geoJSON,
allMapStatistics,
selectedStatistics,
fetchMapStatisticsById,
fetchInitialMapStatistics,
};
};
现在我问自己这是否是执行此操作的最有效方法?我还尝试使用 selectedStatistics 状态执行fetchMapStatisticsById,如下所示:
const fetchMapStatisticsById = useCallback(() => {
getMapStatisticsById({ type: selectedStatistics }) // selectedStatistics is null
.then(result => setGeoJSON(result));
}, [selectedStatistics]);
但这不起作用,因为在 react 中设置状态是异步发生的(selectedStatistics 为空)。所以我想知道通过 id 获取统计信息的状态是否会更好(这对我不起作用)或者只是将统计信息 id 作为参数传递给 useCallback 函数?还可以选择将 selectedStatistics 放在 useRef 中,这将同步更改。这也是一种选择,还是这种反模式?
【问题讨论】:
-
只需将其包装在
if (selectedStatistics != null)中,以防止在尚未加载统计信息时在初始效果调用中获取。
标签: javascript reactjs promise react-hooks