reactjs Vite + React:我的帖子路由在useEffect内多次命中

mmvthczy  于 2023-08-04  发布在  React
关注(0)|答案(2)|浏览(111)

我在我的应用程序中实现了spotify API,然而,如下图所示,post路由被击中2-4次,并不断覆盖所有导致错误的数据。
Repo(如果你需要):https://github.com/kankanrr/post-route
post route hitting multiple times

  1. const client_id = ""; // Your client id
  2. const client_secret = ""; // Your secret
  3. const redirect_uri = "http://localhost:3000/callback";
  4. const [accessToken, setAccessToken] = useState("");
  5. const [refreshToken, setRefreshToken] = useState("");
  6. const [expiresIn, setExpiresIn] = useState("");
  7. useEffect(() => {
  8. const authParams = {
  9. method: "POST",
  10. headers: {
  11. "Content-Type": "application/x-www-form-urlencoded",
  12. Authorization:
  13. "Basic " +
  14. new Buffer.from(client_id + ":" + client_secret).toString("base64"),
  15. },
  16. body: new URLSearchParams({
  17. grant_type: "authorization_code",
  18. redirect_uri: redirect_uri,
  19. code: code,
  20. }),
  21. };
  22. const refreshParams = {
  23. method: "POST",
  24. headers: {
  25. "Content-Type": "application/x-www-form-urlencoded",
  26. Authorization:
  27. "Basic " +
  28. new Buffer.from(client_id + ":" + client_secret).toString("base64"),
  29. },
  30. body: new URLSearchParams({
  31. grant_type: "refresh_token",
  32. refresh_token: refreshToken,
  33. client_id: client_id,
  34. }),
  35. };
  36. fetch("https://accounts.spotify.com/api/token", authParams)
  37. .then((result) => result.json())
  38. .then((data) => {
  39. console.log(data);
  40. if (!accessToken) {
  41. setAccessToken(data.access_token);
  42. }
  43. setRefreshToken(data.refresh_token);
  44. setExpiresIn(data.expires_in);
  45. if (!expiresIn) {
  46. fetch("https://accounts.spotify.com/api/token", refreshParams)
  47. .then((res) => res.json())
  48. .then((data) => {
  49. setExpiresIn(data.expires_in);
  50. setAccessToken(data.access_token);
  51. });
  52. }
  53. console.log(data.access_token);
  54. // if (accessToken) return console.log("access toke +> " + accessToken);
  55. // else window.history.pushState({}, null, "/");
  56. })
  57. .catch((err) => {
  58. console.log(err);
  59. res.sendStatus(400);
  60. });
  61. }, []);

字符串
我只想运行一次,这样我的令牌就不会被覆盖。这个useEffect最初是两个独立的useEffect,但我合并成一个,看看它是否会解决问题。我试着删除React严格模式,只是完全打破了应用程序。我在useeffect中尝试了async rqs。老实说,我不知道这里的问题是什么,为什么它发布多次,并覆盖我的令牌数据。

yfjy0ee7

yfjy0ee71#

在useEffect钩子的依赖数组中添加accessToken和refreshToken。

lpwwtiir

lpwwtiir2#

我不能评论,所以我把它放在这里。
如果你使用React.strictMode在开发模式下运行应用程序,那么任何重新呈现都会触发两次。请参阅此post了解更多信息。
尝试在预览模式下运行应用程序:vite preview并检查问题是否延续到构建中。

相关问题