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

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

Axios return data not updating a list

问题

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

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

以下是代码:

import "./SuggestedClasses.css";
import Axios from "axios";
import { useState, useEffect } from "react";
import TakenClass from "./types";
import {
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  TableContainer,
} from "@chakra-ui/react";

const SuggestedClasses = () => {
  const mapping: Record<number, string> = {
    0: "CI-H",
    1: "CI-M",
    2: "HASS-S",
    3: "HASS-H",
    4: "HASS-A",
  };

  localStorage.setItem("requirements_satisfied", "[2, 2, 1, 1, 1]");
  const requirements_satisfied = JSON.parse(
    localStorage.getItem("requirements_satisfied") as string
  );

  var reqs_filled = JSON.parse(
    localStorage.getItem("requirements_filled") as string
  );

  var reqs_needed: TakenClass[] = [];

  if (localStorage.getItem("requirements_filled") == null) {
    localStorage.setItem("requirements_filled", "[0, 0, 0, 0, 0]");
  }

  for (var i = 0; i < requirements_satisfied.length; i++) {
    if (reqs_filled[i] < requirements_satisfied[i]) {
      var j = 0;
      while (j < requirements_satisfied[i] - reqs_filled[i]) {
        var hass_attribute = null;
        var communication_requirement = null;
        if (mapping[i][0] === "C") {
          hass_attribute = null;
          communication_requirement = mapping[i];
        } else {
          hass_attribute = mapping[i];
          communication_requirement = null;
        }

        useEffect(() => {
          Axios.get("http://localhost:3000/getClass", {
            data: {
              hass_attribute: hass_attribute,
              communication_requirement: communication_requirement,
            },
          }).then((response) => {
            if (response.data) {
              reqs_needed.push(response.data);
            }
          });
        }, []);
        j++;
      }
    }
  }
  // console.log("reqs_needed", reqs_needed);
  console.log("reqs_needed.length", reqs_needed.length);
  for (var i = 0; i < reqs_needed.length; i++) {
    console.log("here");
    console.log("LOOPING", reqs_needed[i]);
  }

  return (
    <div className="suggestedClassesContainer">
      <h4 className="card-header">Suggested Classes</h4>
      <TableContainer>
        <Table variant="striped" colorScheme="teal">
          <Thead>
            <Tr>
              <Th>Num.</Th>
              <Th>Rating</Th>
            </Tr>
          </Thead>
          <Tbody>
            {reqs_needed.map((req: TakenClass) => {
              if (req != null) {
                return (
                  <Tr>
                    <Td>{req.subject_id}</Td>
                    <Td>{req.rating}</Td>
                  </Tr>
                );
              }
            })}
          </Tbody>
        </Table>
      </TableContainer>
    </div>
  );
};

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:

import &quot;./SuggestedClasses.css&quot;;
import Axios from &quot;axios&quot;;
import { useState, useEffect } from &quot;react&quot;;
import TakenClass from &quot;./types&quot;;
import {
Table,
Thead,
Tbody,
Tr,
Th,
Td,
TableContainer,
} from &quot;@chakra-ui/react&quot;;
const SuggestedClasses = () =&gt; {
const mapping: Record&lt;number, string&gt; = {
0: &quot;CI-H&quot;,
1: &quot;CI-M&quot;,
2: &quot;HASS-S&quot;,
3: &quot;HASS-H&quot;,
4: &quot;HASS-A&quot;,
};
localStorage.setItem(&quot;requirements_satisfied&quot;, &quot;[2, 2, 1, 1, 1]&quot;);
const requirements_satisfied = JSON.parse(
localStorage.getItem(&quot;requirements_satisfied&quot;) as string
);
var reqs_filled = JSON.parse(
localStorage.getItem(&quot;requirements_filled&quot;) as string
);
var reqs_needed: TakenClass[] = [];
if (localStorage.getItem(&quot;requirements_filled&quot;) == null) {
localStorage.setItem(&quot;requirements_filled&quot;, &quot;[0, 0, 0, 0, 0]&quot;);
}
for (var i = 0; i &lt; requirements_satisfied.length; i++) {
if (reqs_filled[i] &lt; requirements_satisfied[i]) {
var j = 0;
while (j &lt; requirements_satisfied[i] - reqs_filled[i]) {
var hass_attribute = null;
var communication_requirement = null;
if (mapping[i][0] === &quot;C&quot;) {
hass_attribute = null;
communication_requirement = mapping[i];
} else {
hass_attribute = mapping[i];
communication_requirement = null;
}
useEffect(() =&gt; {
Axios.get(&quot;http://localhost:3000/getClass&quot;, {
data: {
hass_attribute: hass_attribute,
communication_requirement: communication_requirement,
},
}).then((response) =&gt; {
if (response.data) {
reqs_needed.push(response.data);
}
});
}, []);
j++;
}
}
}
// console.log(&quot;reqs_needed&quot;, reqs_needed);
console.log(&quot;reqs_needed.length&quot;, reqs_needed.length);
for (var i = 0; i &lt; reqs_needed.length; i++) {
console.log(&quot;here&quot;);
console.log(&quot;LOOPING&quot;, reqs_needed[i]);
}
return (
&lt;div className=&quot;suggestedClassesContainer&quot;&gt;
&lt;h4 className=&quot;card-header&quot;&gt;Suggested Classes&lt;/h4&gt;
&lt;TableContainer&gt;
&lt;Table variant=&quot;striped&quot; colorScheme=&quot;teal&quot;&gt;
&lt;Thead&gt;
&lt;Tr&gt;
&lt;Th&gt;Num.&lt;/Th&gt;
&lt;Th&gt;Rating&lt;/Th&gt;
&lt;/Tr&gt;
&lt;/Thead&gt;
&lt;Tbody&gt;
{reqs_needed.map((req: TakenClass) =&gt; {
if (req != null) {
return (
&lt;Tr&gt;
&lt;Td&gt;{req.subject_id}&lt;/Td&gt;
&lt;Td&gt;{req.rating}&lt;/Td&gt;
&lt;/Tr&gt;
);
}
})}
&lt;/Tbody&gt;
&lt;/Table&gt;
&lt;/TableContainer&gt;
&lt;/div&gt;
);
};
export default SuggestedClasses;

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

答案1

得分: 0

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

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

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

setReqNeeded[response.data]

希望这对你有所帮助!

英文:

use state and add data inside that
for example -

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

insert the data inside the set useState -

setReqNeeded[response.data]

Hope it will help!!

答案2

得分: 0

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

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

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

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

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

然后设置它:

setReqsNeeded(newData);

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

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

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

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

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

所以,代码会像这样:

useEffect(() => {
  const newReqsNeeded = [];

  // 加载数据
  for (...) {
    // ...
    newReqsNeeded.push(newValue);
  }

  // 最后更新状态
  setReqsNeeded(newReqsNeeded);
}, []);

你应该注意到,我使用了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:

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

And then set it:

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:

useEffect(() =&gt; {
// load data
}, []);

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:

useEffect(() =&gt; {
const newReqsNeeded = [];
// load data
for (...) {
// ...
newReqsNeeded.push(newValue);
}
// finally update the state
setReqsNeeded(newReqsNeeded);
}, []);

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:

确定