gpt4 book ai didi

javascript - 在 useState Hook 中使用 SWR 数据

转载 作者:行者123 更新时间:2023-12-05 02:38:57 25 4
gpt4 key购买 nike

  const fetcher = (url: string) => fetch(url).then((r) => r.json());

const { data, error } = useSWR(
"https://some.com/api",
fetcher,
);

有没有办法像这样在 useState 钩子(Hook)中添加数据

  const fetcher = (url: string) => fetch(url).then((r) => r.json());

const { data, error } = useSWR(
"https://meme-api.herokuapp.com/gimme/5",
fetcher,
);

const [memes,setMemes]=useState(data);

因为我想在某个时间点连接数据以进行无限滚动

最佳答案

因为 https://meme-api.herokuapp.com/gimme/5 每次调用总是返回新数据,useSWR 不适合这个而且,此外,它从缓存中检索并将其提供给您的代码,然后重新验证并(可能)调用您的代码进行更新,而不告诉您这是第一个结果还是更新,这使得您很难做重新描述。

相反,我只是直接使用 fetch 而不是尝试做 SWR 的事情;看评论:

// Start with no memes
const [memes,setMemes] = useState([]);

// Use a ref to track an `AbortController` so we can:
// A) avoid overlapping fetches, and
// B) abort the current `fetch` operation (if any) on unmount
const fetchControllerRef = useRef(null);

// A function to fetch memes
const fetchMoreMemes = () => {
if (!fetchControllerRef.current) {
fetchControllerRef.current = new AbortController();
fetch("https://meme-api.herokuapp.com/gimme/5", {signal: fetchControllerRef.current.signal})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.json();
})
.then(newMemes => {
setMemes(memes => memes.concat(newMemes.memes));
})
.catch(error => {
// ...handle/report error...
})
.finally(() => {
fetchControllerRef.current = null;
});
}
};

// Fetch the first batch of memes
useEffect(() => {
fetchMoreMemes();
return () => {
// Cancel the current `fetch` (if any) when the component is unmounted
fetchControllerRef.current?.abort();
};
}, []);

当你想获取更多模因时,调用fetchMoreMemes

实例:

const {useState, useEffect, useRef} = React;

const Example = () => {
// Start with no memes
const [memes,setMemes] = useState([]);

// Use a ref to track an `AbortController` so we can:
// A) avoid overlapping fetches, and
// B) abort the current `fetch` operation (if any) on unmount
const fetchControllerRef = useRef(null);

// A function to fetch memes
const fetchMoreMemes = () => {
if (!fetchControllerRef.current) {
fetchControllerRef.current = new AbortController();
fetch("https://meme-api.herokuapp.com/gimme/5", {signal: fetchControllerRef.current.signal})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.json();
})
.then(newMemes => {
// I'm filtering out NSFW ones here on SO
setMemes(memes => memes.concat(newMemes.memes.filter(({nsfw}) => !nsfw)));
})
.catch(error => {
// ...handle/report error...
})
.finally(() => {
fetchControllerRef.current = null;
});
}
};

// Fetch the first batch of memes
useEffect(() => {
fetchMoreMemes();
return () => {
// Cancel the current `fetch` (if any) when the component is unmounted
fetchControllerRef.current && fetchControllerRef.current.abort();
};
}, []);

const message = memes.length === 1 ? "1 meme:" : `${memes.length} memes:`;
return <div>
<div>{message} <input type="button" value="More" onClick={fetchMoreMemes}/></div>
<ul>
{/* `index` as key is ONLY valid because our array only grows */}
{memes.map(({postLink}, index) => <li key={index}>{postLink}</li>)}
</ul>
</div>
};


ReactDOM.render(<Example />, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

关于javascript - 在 useState Hook 中使用 SWR 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69345572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com