如何获取和重新呈现组件

时间:2020-06-17 12:44:43

标签: reactjs react-hooks

请告诉我如何使用useState将新数据提取到数组中。 每次使用useEffect时,该数组都会再次初始化为空。我需要将此数组传递给表,以便在值更改时再次呈现该表。

const AccountContainer = () => {
  let [isLoaded, setIsLoaded] = useState(false);
  let [page, setPage] = useState(0);
  let [accData, setAccData] = useState([]);
  useEffect(() => {loadData()}, [page]);

  const loadData = async () => {
    const response = await fetch(API_URL);
    const data = await response.json();
     data.content.map(acc => {     
       setAccData([...accData, acc])
    });

    setIsLoaded(true);
  };


 return (
          <table data={accData} />
 )
};

export default AccountContainer;

添加了日志

[]          AccountContainer.js:30
[]          AccountContainer.js:30
[]          AccountContainer.js:30
[]          AccountContainer.js:30
[]          AccountContainer.js:30
[]          AccountContainer.js:30

https://codesandbox.io/embed/great-rubin-poywh?fontsize=14&hidenavigation=1&theme=dark

预先感谢

1 个答案:

答案 0 :(得分:1)

这是PlatformEffect

中的解决方案
// AccountList.jsx
import React from "react";

const AccountList = props => (
  <div>
    {console.warn(props)}
    {props.dataAcc.map(acc => (
      <div>{acc.email}</div>
    ))}
    )
  </div>
);

export default AccountList;

App.jsx

import React, { useState, useEffect } from "react";
import AccountList from "./AccountList";
import "./styles.css";

const AccountContainer = () => {
  let [isLoaded, setIsLoaded] = useState(false);
  let [page, setPage] = useState(0);
  let [accData, setAccData] = useState([]);
  const API_URL = `https://reqres.in/api/users?page=1`;

  useEffect(() => {
    loadData();
  }, [page]);

  const loadData = async () => {
    const response = await fetch(API_URL);
    const data = await response.json();
    setAccData([...accData, ...data.data]);
    setIsLoaded(true);
  };

  const renderTable = () => {
    if (isLoaded) {
      return (
        <div>
          {console.warn(accData)}
          <AccountList dataAcc={accData} />
        </div>
      );
    } else if (!isLoaded) return "Loading";
  };

  return renderTable();
};

export default AccountContainer;