简体   繁体   English

为什么 useState 不更新数据?

[英]why useState is not updating data?

I am very new to react and after taking a course, I just wanted to do a project in react that I already did in Vue earlier just to practice React.我对 react 很陌生,在学习完课程后,我只想做一个我之前在 Vue 中已经做过的 react 项目,只是为了练习 React。 But my useState is not updating the data that I want to list out.但是我的 useState 没有更新我想要列出的数据。

The data from api is an array of Objects.来自 api 的数据是一个对象数组。 End goal is to make a data table.最终目标是制作数据表。 So to be dynamic, I took the keys of the first object to take the column names.所以为了动态,我取了第一个 object 的键来取列名。 I used DataTable from 'react-data-table-component' for the data table.我使用“react-data-table-component”中的 DataTable 作为数据表。 That didn't work.那没有用。 Now just to debug I thought to list out the column names but that didn't work either but it console logs.现在只是为了调试,我想列出列名,但这也不起作用,但它控制台日志。

I know this is something very basic and have searched lot of help in the internet and tried to solve who faced similar issue from lot of portals but nothing helped so far.我知道这是非常基本的事情,并且在互联网上搜索了很多帮助,并试图解决谁面临许多门户网站的类似问题,但到目前为止没有任何帮助。 Where am I doing wrong?我在哪里做错了?

import React, { useState, useEffect, Component } from 'react'; 
import axios from 'axios'


const tableData = () => {
    const [tableData, setTableData] = useState([]);
    const [columns, setColumns] = useState([])

    useEffect(() => {
        axios.get('http://localhost:4000/')
            .then((res) => {
                if (res.status === 200) {
                    if (res.data === 0) {
                        console.log("Something is wrong !!!");
                    } else {
                        const data = res.data['rows']
                        const columns = Object.keys(data[0])
                        console.log(columns)
                        setTableData(data)
                        setColumns(columns)
                    }
                }
            }).catch(error => {
                console.log(error)
            })
    }, [])

    return (
        <div>
            <ul>
            {columns.map((columnName, index) => {
                const {name} = columnName;
                return (
                        <li key={index}>{ name }</li>
                       )
            })}
            </ul>
        </div>
    ) 
} 

in react state, set state works on references.在反应 state 中,设置 state 适用于参考。 sometime we need to change the state to the same reference that we changed the value of it.有时我们需要将 state 更改为与我们更改它的值相同的参考。 so instead put the same reference as an argument, we need to set a copy of it, because if we will set to the same state that already in the state, react can not see any different so it will not render again.所以改为将相同的引用作为参数,我们需要设置它的副本,因为如果我们将设置为已经在 state 中的相同 state,react 看不到任何不同,因此它不会再次渲染。

in your example, you didn't use the same reference for data, but for columns you used the same name of the state and the new columns.在您的示例中,您没有对数据使用相同的引用,但对于列,您使用了相同名称的 state 和新列。

example:例子:

let referenceName = 'John';让referenceName = '约翰';

const [name, setName] = useState(referenceName); const [名称,setName] = useState(referenceName);

referenceName = 'Johnny'参考名称 = '约翰尼'

setName(...referenceName )设置名称(...参考名称)

I want to set the name of the state, but if i will NOT use the '...', react will not see any difference because i use the same reference.. so I need to put a copy od the refence for set a new reference.我想设置 state 的名称,但如果我不使用“...”,反应不会看到任何区别,因为我使用相同的引用..所以我需要复制 od 设置的引用新的参考。

  1. check the shape of response data here I simpliplified the useEffect by call that function out side在这里检查响应数据的形状我通过调用 function 简化了 useEffect
    import React, { useState, useEffect, Component } from "react";
    import axios from "axios";
    
    const tableData = () => {
      const [tableData, setTableData] = useState([]);
      const [columns, setColumns] = useState([]);
    
      const fetchDetails = () => {
        axios
          .get("http://localhost:4000/")
          .then((res) => {
            const data = res.data["rows"];
            const columns = Object.keys(data[0]);
            console.log(columns);
            setTableData(data);
            setColumns(columns);
          })
          .catch((error) => {
            //dont need to check the status if any occurs it will come to this catch block
            console.log(error.message);
          });
      };
    
      useEffect(() => {
        fetchDetails();
      }, [columns]);
    
      return (
        <div>
          <ul>
            {columns.map((columnName, index) => {
              const { name } = columnName;
              return <li key={index}>{name}</li>;
            })}
          </ul>
        </div>
      );
    };

can you try this block of code你能试试这段代码吗

 const [tableData, setTableData] = useState([]);
    const [columns, setColumns] = useState([])
    const [status , setStatus] = useState("idle")

  const fetchData = async()=>{
    try{
      setStatus("loading")
    const getFetch = await fetch('http://localhost:4000/')
    const convertToJson = await getData.json()
    const data = convertToJson.data['rows']
                        const getColumns = Object.keys(data[0])
                        console.log(getColumns)
                        setTableData(data)
                        setColumns(getColumns)
                        setStatus("success")
}catch(er){
  console.log("something wrong")
  setStatus("error")
}   
}
  React.useEffect(()=>{
   fetchData()
},[])

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

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