Axios返回的数据未更新列表。

huangapple go评论110阅读模式
英文:

Axios return data not updating a list

问题

我有这个名为reqs_needed的列表。我想根据Axios请求返回的信息来更新它。这个Axios.get请求位于一个for循环中,因为我想获取特定次数的数据。然而,当我尝试将数据添加到它时,我的req_needed没有被添加。

我的后端正常运行,因为我可以成功地将数据发送回前端并且它会正确打印。只是根本没有添加到列表中。

以下是代码:

  1. import "./SuggestedClasses.css";
  2. import Axios from "axios";
  3. import { useState, useEffect } from "react";
  4. import TakenClass from "./types";
  5. import {
  6. Table,
  7. Thead,
  8. Tbody,
  9. Tr,
  10. Th,
  11. Td,
  12. TableContainer,
  13. } from "@chakra-ui/react";
  14. const SuggestedClasses = () => {
  15. const mapping: Record<number, string> = {
  16. 0: "CI-H",
  17. 1: "CI-M",
  18. 2: "HASS-S",
  19. 3: "HASS-H",
  20. 4: "HASS-A",
  21. };
  22. localStorage.setItem("requirements_satisfied", "[2, 2, 1, 1, 1]");
  23. const requirements_satisfied = JSON.parse(
  24. localStorage.getItem("requirements_satisfied") as string
  25. );
  26. var reqs_filled = JSON.parse(
  27. localStorage.getItem("requirements_filled") as string
  28. );
  29. var reqs_needed: TakenClass[] = [];
  30. if (localStorage.getItem("requirements_filled") == null) {
  31. localStorage.setItem("requirements_filled", "[0, 0, 0, 0, 0]");
  32. }
  33. for (var i = 0; i < requirements_satisfied.length; i++) {
  34. if (reqs_filled[i] < requirements_satisfied[i]) {
  35. var j = 0;
  36. while (j < requirements_satisfied[i] - reqs_filled[i]) {
  37. var hass_attribute = null;
  38. var communication_requirement = null;
  39. if (mapping[i][0] === "C") {
  40. hass_attribute = null;
  41. communication_requirement = mapping[i];
  42. } else {
  43. hass_attribute = mapping[i];
  44. communication_requirement = null;
  45. }
  46. useEffect(() => {
  47. Axios.get("http://localhost:3000/getClass", {
  48. data: {
  49. hass_attribute: hass_attribute,
  50. communication_requirement: communication_requirement,
  51. },
  52. }).then((response) => {
  53. if (response.data) {
  54. reqs_needed.push(response.data);
  55. }
  56. });
  57. }, []);
  58. j++;
  59. }
  60. }
  61. }
  62. // console.log("reqs_needed", reqs_needed);
  63. console.log("reqs_needed.length", reqs_needed.length);
  64. for (var i = 0; i < reqs_needed.length; i++) {
  65. console.log("here");
  66. console.log("LOOPING", reqs_needed[i]);
  67. }
  68. return (
  69. <div className="suggestedClassesContainer">
  70. <h4 className="card-header">Suggested Classes</h4>
  71. <TableContainer>
  72. <Table variant="striped" colorScheme="teal">
  73. <Thead>
  74. <Tr>
  75. <Th>Num.</Th>
  76. <Th>Rating</Th>
  77. </Tr>
  78. </Thead>
  79. <Tbody>
  80. {reqs_needed.map((req: TakenClass) => {
  81. if (req != null) {
  82. return (
  83. <Tr>
  84. <Td>{req.subject_id}</Td>
  85. <Td>{req.rating}</Td>
  86. </Tr>
  87. );
  88. }
  89. })}
  90. </Tbody>
  91. </Table>
  92. </TableContainer>
  93. </div>
  94. );
  95. };
  96. export default SuggestedClasses;

reqs_needed的长度总是为零,导致我的前端表格中什么都没有显示出来。

英文:

I have this list called reqs_needed. I want to update it based on the information an Axios request returns. This Axios.get request is inside a for loop because I want to get data back a certain number of times. However, my req_needed is not getting pushed to after I try pusing data to it.

My backend works fine as I can successfully send data back to the frontend and it will print correctly. It's just not adding to the list at all.

Here is the code:

  1. import &quot;./SuggestedClasses.css&quot;;
  2. import Axios from &quot;axios&quot;;
  3. import { useState, useEffect } from &quot;react&quot;;
  4. import TakenClass from &quot;./types&quot;;
  5. import {
  6. Table,
  7. Thead,
  8. Tbody,
  9. Tr,
  10. Th,
  11. Td,
  12. TableContainer,
  13. } from &quot;@chakra-ui/react&quot;;
  14. const SuggestedClasses = () =&gt; {
  15. const mapping: Record&lt;number, string&gt; = {
  16. 0: &quot;CI-H&quot;,
  17. 1: &quot;CI-M&quot;,
  18. 2: &quot;HASS-S&quot;,
  19. 3: &quot;HASS-H&quot;,
  20. 4: &quot;HASS-A&quot;,
  21. };
  22. localStorage.setItem(&quot;requirements_satisfied&quot;, &quot;[2, 2, 1, 1, 1]&quot;);
  23. const requirements_satisfied = JSON.parse(
  24. localStorage.getItem(&quot;requirements_satisfied&quot;) as string
  25. );
  26. var reqs_filled = JSON.parse(
  27. localStorage.getItem(&quot;requirements_filled&quot;) as string
  28. );
  29. var reqs_needed: TakenClass[] = [];
  30. if (localStorage.getItem(&quot;requirements_filled&quot;) == null) {
  31. localStorage.setItem(&quot;requirements_filled&quot;, &quot;[0, 0, 0, 0, 0]&quot;);
  32. }
  33. for (var i = 0; i &lt; requirements_satisfied.length; i++) {
  34. if (reqs_filled[i] &lt; requirements_satisfied[i]) {
  35. var j = 0;
  36. while (j &lt; requirements_satisfied[i] - reqs_filled[i]) {
  37. var hass_attribute = null;
  38. var communication_requirement = null;
  39. if (mapping[i][0] === &quot;C&quot;) {
  40. hass_attribute = null;
  41. communication_requirement = mapping[i];
  42. } else {
  43. hass_attribute = mapping[i];
  44. communication_requirement = null;
  45. }
  46. useEffect(() =&gt; {
  47. Axios.get(&quot;http://localhost:3000/getClass&quot;, {
  48. data: {
  49. hass_attribute: hass_attribute,
  50. communication_requirement: communication_requirement,
  51. },
  52. }).then((response) =&gt; {
  53. if (response.data) {
  54. reqs_needed.push(response.data);
  55. }
  56. });
  57. }, []);
  58. j++;
  59. }
  60. }
  61. }
  62. // console.log(&quot;reqs_needed&quot;, reqs_needed);
  63. console.log(&quot;reqs_needed.length&quot;, reqs_needed.length);
  64. for (var i = 0; i &lt; reqs_needed.length; i++) {
  65. console.log(&quot;here&quot;);
  66. console.log(&quot;LOOPING&quot;, reqs_needed[i]);
  67. }
  68. return (
  69. &lt;div className=&quot;suggestedClassesContainer&quot;&gt;
  70. &lt;h4 className=&quot;card-header&quot;&gt;Suggested Classes&lt;/h4&gt;
  71. &lt;TableContainer&gt;
  72. &lt;Table variant=&quot;striped&quot; colorScheme=&quot;teal&quot;&gt;
  73. &lt;Thead&gt;
  74. &lt;Tr&gt;
  75. &lt;Th&gt;Num.&lt;/Th&gt;
  76. &lt;Th&gt;Rating&lt;/Th&gt;
  77. &lt;/Tr&gt;
  78. &lt;/Thead&gt;
  79. &lt;Tbody&gt;
  80. {reqs_needed.map((req: TakenClass) =&gt; {
  81. if (req != null) {
  82. return (
  83. &lt;Tr&gt;
  84. &lt;Td&gt;{req.subject_id}&lt;/Td&gt;
  85. &lt;Td&gt;{req.rating}&lt;/Td&gt;
  86. &lt;/Tr&gt;
  87. );
  88. }
  89. })}
  90. &lt;/Tbody&gt;
  91. &lt;/Table&gt;
  92. &lt;/TableContainer&gt;
  93. &lt;/div&gt;
  94. );
  95. };
  96. export default SuggestedClasses;

The length of reqs_needed is always zero and causes nothing to show up in my frontend table.

答案1

得分: 0

使用状态并在其中添加数据
例如 -

  1. const [reqNeeded, setReqNeeded] = useState([])

将数据插入到设置的useState中 -

  1. setReqNeeded[response.data]

希望这对你有所帮助!

英文:

use state and add data inside that
for example -

  1. const [reqNeeded, setReqNeeded] = useState([])

insert the data inside the set useState -

  1. setReqNeeded[response.data]

Hope it will help!!

答案2

得分: 0

很明显,你对React还不熟悉,所以最好先学习React的基础知识。

但是为了回答你的具体问题,它不会更新是因为React组件只有在其状态或属性更新时才会重新渲染。

你的reqs_needed只是组件内部的一个变量,更新变量不会重新渲染组件(也就是说,不会重新绘制它),因为它不是一个状态变量。

所以,你需要将它定义为一个状态变量,像这样:

  1. const [reqsNeeded, setReqsNeeded] = useState([]);

然后设置它:

  1. setReqsNeeded(newData);

但是直接在函数体内加载所有数据也不是一个好主意,因为它会在每次页面重新渲染时重新运行,所以你需要将它放在useEffect块中,像这样:

  1. useEffect(() => {
  2. // 加载数据
  3. }, []);

带有[]作为第二个参数的useEffect块只在组件挂载时运行一次,所以你可以避免反复加载数据。

但是,你想要在迭代中获取数据并将它们全部推送到reqs_needed中,而设置状态是不可变的,这意味着你不能直接编辑reqsNeeded状态,而是要设置一个新的状态。

所以,你应该将所有数据存储在一个局部变量中,然后在变量准备好后调用setReqsNeeded

所以,代码会像这样:

  1. useEffect(() => {
  2. const newReqsNeeded = [];
  3. // 加载数据
  4. for (...) {
  5. // ...
  6. newReqsNeeded.push(newValue);
  7. }
  8. // 最后更新状态
  9. setReqsNeeded(newReqsNeeded);
  10. }, []);

你应该注意到,我使用了camelCase而不是lower_case_with_hyphen,因为在JS中,我们通常使用前者的命名模式。而且,如果我们将最终的状态变量命名为reqs_needed,setter方法的名称将会很奇怪,为setreqs_needed,这看起来不好。

无论如何,正如你所看到的,你的代码中有很多问题,最好先查看React文档

英文:

Obviously, you're new to React so it's best to learn basics of React first.

But to answer your specific question, it's not updating because a React component does not re-render until its states or props are updated.

Your reqs_needed is just a variable inside your component and updating the variable does not re-render the component (meaning, re-draw it) because it's not a state variable.

So, you need to define it as a state variable like this:

  1. const [reqsNeeded, setReqsNeeded] = useState([]);

And then set it:

  1. setReqsNeeded(newData);

But loading all data directly inside the function body is not a good idea either because it'll be re-run each time page re-renders, so you need to put it in useEffect block like this:

  1. useEffect(() =&gt; {
  2. // load data
  3. }, []);

useEffect block with [] as second param runs only once at the start when your component mounts, so you can avoid re-loading data again and again.

But, you want to pull data in an iteration and push all of them to reqs_needed, and setting the state is immutable which means you can't edit the reqsNeeded state directly but setting a new state.

So, you'd want to store all of your data in a local variable and then call setReqsNeeded at the end when the variable is ready.

So, it'll look like this:

  1. useEffect(() =&gt; {
  2. const newReqsNeeded = [];
  3. // load data
  4. for (...) {
  5. // ...
  6. newReqsNeeded.push(newValue);
  7. }
  8. // finally update the state
  9. setReqsNeeded(newReqsNeeded);
  10. }, []);

You should notice I used camelCase rather than lower_case_with_hyphen because in JS, we usually use the former name pattern. Plus, if we name the final state variable reqs_needed, the setter method name will be weirdly setreqs_needed, which doesn't look good.

Anyway, as you can see, there are many problems in your code and it's best to look at the React documentation first.

huangapple
  • 本文由 发表于 2023年6月5日 10:28:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定