简体   繁体   English

反应:钩子没有得到新数据

[英]React : Hook doesn't get new data

I'm fetching data using axios in React .我在React中使用axios获取数据。

const [ListProfil, setListProfil] = React.useState([]);  

useEffect(() => {
    axios
        .get("http://localhost:8000/api/profile/selected/10")
        .then((response) => setTimeout(()=>{
            setListProfil(response.data.data);
            console.log(response);
        }, 0))
        .catch((err) => console.log(err));
}, []);

The array that is returned have two elements:返回的数组有两个元素:

在此处输入图像描述

Now when I'm adding a new element with onAdd , the axios request to POST is executed without problem.现在,当我使用onAdd添加新元素时,对POST的 axios 请求可以毫无问题地执行。 And after sending the POST request I'm sending a second request GET to retrieve the new data directly from database.在发送POST请求后,我将发送第二个请求GET以直接从数据库中检索新数据。

 const onAdd = (e) => {
        e.preventDefault();

        const infos = {
            username: username,
            user_id: 10,
            p_color: "#ffffff",
            country: "ma",
            address: "zezefez",
        };

        console.log(infos);

        axios
            .post("http://localhost:8000/api/profile/", infos)
            .then((res) => {
                toast(
                    <div class="text-primary font-weight-bolder">
                        Social link added successfully!
                    </div>,
                    { delay: 0 }
                );
                console.log(res);
            })
            .catch((error) => {
                console.log(error);
            });
            
        axios
            .get("http://localhost:8000/api/profile/selected/10")
            .then((response) => setTimeout(()=>{
                setListProfil(response.data.data);console.log(response);  console.log(ListProfil);
            }, 0))
            .catch((err) => console.log(err));     

    };

The problem here is when I get the data the second time, React doesn't set it in the hook as he did the first time.这里的问题是当我第二次获取数据时, React并没有像第一次那样将它设置在钩子中。

Meaning that I'm getting the data from database correctly, but the array inside the hook that is supposed to receive the new data still have the old data.这意味着我正确地从数据库中获取数据,但是应该接收新数据的钩子内的数组仍然有旧数据。 I tried setting a second different hook but it didn't work.我尝试设置第二个不同的钩子,但它没有用。

BUT surprisely it will receive the data AFTER I create a second element or refresh the page.令人惊讶的是,它会在我创建第二个元素或刷新页面接收数据。

So I'm constantly having a delayed list inside the array of所以我经常在数组中有一个延迟列表

const [ListProfil, setListProfil] = React.useState([]);

How can I have the new data from the database inside the hook?如何在钩子内获取数据库中的新数据?

In the following image:在下图中:

1- The added element with username : testing_new_profile
2- The console.log(ListProfil) returning the final new array.
3- -----
4- The received data from database, note that there is the new element present because `Array(3)`.
5- The console.log(ListProfil) still returning the old array even after getting the new array from database.

在此处输入图像描述

after sending the POST request I'm sending a second request GET to retrieve the new data directly from database.发送 POST 请求后,我将发送第二个请求 GET 以直接从数据库中检索新数据。

You are not actually doing this because the code runs asynchronously.您实际上并没有这样做,因为代码是异步运行的。 What is actually happening is that both your POST and GET run at the same time, then the results come back in whatever order they come back in, triggering their respective then blocks.实际发生的情况是您的 POST 和 GET 同时运行,然后结果以它们返回的任何顺序返回,触发它们各自的then块。

If you want them to run sequentially you need to wait for the POST call to finish then you fire your GET call:如果您希望它们按顺序运行,则需要等待 POST 调用完成,然后触发 GET 调用:

axios.post(...)
  .then(...)
  .then(() => {
    return axios.get(...).then(...)
  })
  .catch(...)

Here is a great article on promises I always recommend 这是一篇关于我一直推荐的承诺的好文章

For anyone interested this is how I solved it and retrieved the last element of the new list that I get with axios post :对于任何感兴趣的人,这就是我如何解决它并检索我通过 axios post获得的新列表的最后一个元素:

    axios
        .get("http://localhost:8000/api/profile/selected/10")
        .then((response) => {
            setListProfil(response.data.data);          
    let newData= [response.data.data.slice(-1)[0]];
    let idData= newData[0];
    let ok = idData.id;

Seeing that I was getting the right data from the database but I was failing at storing it in the hooks, I created a new let newData where I will be receiving response.data.data directly AND at the same time added .slice(-1)[0] in the same line to get the last element of the list.看到我从数据库中获取了正确的数据,未能将其存储在挂钩中,我创建了一个新的let newData ,我将在其中直接接收response.data.data并同时添加.slice .slice(-1)[0]在同一行中获取列表的最后一个元素。

After that, the output of newData is a single array of the last element of the new list with an index of 0.之后,newData 的newData是索引为 0 的新列表的最后一个元素的单个数组。

Now I should get the first and only array available with newData[0] and store it in idData .现在我应该得到第一个也是唯一一个可用于newData[0]的数组并将其存储在idData中。

And finally to get the id of that array idData.id .最后获取该数组idData.idid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM