简体   繁体   English

React 不会在初始加载时将数据加载到组件中

[英]React does not load data into component on Initial load

I'm having issues with loading data into the React functional component from API ( getAllUsers() is using the AXIOS library to call PHP rest APIs) on initial load.我在初始加载时将数据从 API 加载到 React 功能组件时遇到问题( getAllUsers()使用 AXIOS 库调用 PHP rest API)。 On 2nd load, it's working.在第二次加载时,它正在工作。 See the attached image.请参阅附图。 加载数据问题反应

How can I modify it to load data on the initial load?如何修改它以在初始加载时加载数据?

Here is the component code snippets:以下是组件代码片段:


*****imports******

function Listallusers (props) {
    
    
    const { rootState,getAllUsers } = useContext(MyContext);
    const { isAuth,showLogin } = rootState;
    let [rows] = useState([]);
    const columns = [...];
    

    useEffect(() => {
      const Userdata = async() => {
        const data = await getAllUsers().then(t => { return t });
        for (const [index, value] of data.entries()) {
            rows.push(value);
        }        
      };
      Userdata();
    }, [getAllUsers, rows]);
   
    if(isAuth){
        return (
            <div className="wrapper">                    
                <Header />
                <Sidebar />
                <div className="content-wrapper" style={{ minHeight: '960px' }}>
                    <section className="content">
                        <div className="container-fluid">
                            <div className="card">
                                <div className="card-body">
                                <DataTable
                                    title="Registered Users"
                                    columns={columns}
                                    data={rows}
                                    striped={true}
                                    responsive={true}
                                    pagination={true}
                                />
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
                <Footer />
            </div>
        ); 
    }
    // Showing Login Or Register Page According to the condition
    else if(showLogin) {
        return <Login/>;
    }
    else {
        return <Register/>;
    }
  }
  
export default Listallusers;

you need to call setState to show render the data on-screen;您需要调用 setState 以在屏幕上显示渲染数据;

useEffect(() => {
  const Userdata = async() => {
    const data = await getAllUsers().then(t => { return t });
    let newRows = [...rows];
    for (const [index, value] of data.entries()) {
      newRows.push(value);
    }  
    setRows(newRows);
  };
  Userdata();
}, [getAllUsers, rows]);

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

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