簡體   English   中英

React JS - 無法在尚未安裝的組件上調用 setState

[英]React JS - setState cannot be called on a component not yet mounted

我在 React JS 中有我的應用程序。 我正在從 http://localhost:8080/api/suppliers/supplier/list 的 API 獲取數據:

這是我從 Google Chrome 控制台中的 REST API 獲得的數據:

0:{
    id: 4
    supplierFirstname: "Tom"
    supplierLastName: "ABC"
    supplierTitle: "TomTheSupplier"
    accountNumber: 1122234444
    address: "111 ADrive, 1234 ST."
    companyName: "TheTom Company & Associates"
    email: "tomtomjayjay@email.com"
    hourlyRate: 29
    phoneNumber: 123456789
    otherPhoneNumber: 1023456789
    paymentTerms: "Credit"
    notes: "Some Supplier"
    createdAt: null
    typeOfGoods: "Supplies"
    website: "www.abc_123.com"
    products: [{…}]
    components: 
        [
            0: {id: 5, name: "AComponent", unit: null, quantity: 0, componentCost: 0, …}
        ]
    
}

這是我的反應代碼:

class SupplierData extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      supplier: [
        {
          id: 0,
          supplierTitle: "Supplier Title",
          supplierFirstName: "First Name",
          supplierLastName: "Last Name",
          companyName: "Company Name",
          phoneNumber: "Phone Number",
          otherPhoneNumber: "Phone Number (Other)",
          accountNumber: "Account Number",
          email: "Email",
          address: "Address",
          website: "Website",
          hourlyRate: "Hourly Rate",
          typeOfGoods: "Type Of Goods",
          paymentTerms: "Payment Terms",
          createdAt: "Created At",
          notes: "Notes",
          products: "Products",
          components: "Components",
        },
      ],
      errorMessage: [],
    };
    
  }

  listAllSuppliers = async () => {
    return await axios
      .get(`http://localhost:8080/api/suppliers/supplier/list`)
      .then((response) => {
        let apiResults = response.data;
        console.log(apiResults);
        this.setState({ supplier: apiResults });    <--- The error happens here.
      })
      .catch((error) => {
        this.setState({ errorMessage: this.state.errorMessage.push(error) });
      });
  };

  componentDidMount() {
    this.ListAllSuppliers();
  }
}

export default SupplierData;

我面臨的問題是在 React State 中。 我收到以下錯誤:

Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might 
         indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = 
         {};` class property with the desired state in the SupplierData component.

問題1:(非常重要)我想設置state。

有什么可能解決上述錯誤?

問題2:在下面的文件中調用上面的class是不是正確的方法。 我有以下代碼:

    import SupplierData from './..';



    export const A = (props) =>{
    const {id, supplierTitle, supplierFirstName, supplierLastName, 
           companyName, phoneNumber, otherPhoneNumber, accountNumber, email, 
           address, website, hourlyRate, typeOfGoods, paymentTerms, 
           createdAt, notes, products, components, status } = props;


       let mySupplier = new SupplierData();
       let listData = mySupplier.listAllSuppliers();


       return(
        <tr>
            <td>
                <Card.Link as={Link} to={Routes.Suppliers.path} className="fw-normal">
                   {SupplierData.map((t, id) => <tr key={id}> {t.fetchedData} </tr>)}  <--- Here is where the error is
                </Card.Link>
            </td>
         </tr>
       );
    }
}

解決問題 2 是解決問題 1 的方法,所以我將回答問題 2:

不,這絕對不是調用 React 組件的正確方法。

SupplierData是一個 React 組件,由於您已經擁有調用listAllSuppliers()componentDidMount()生命周期方法,因此您需要做的就是掛載一個SupplierData組件:

import SupplierData from "./..";

export const A = (props) => {
  return (
    <tr>
      <td>
        <Card.Link as={Link} to={Routes.Suppliers.path} className="fw-normal">
          <SupplierData />
        </Card.Link>
      </td>
    </tr>
  );
};

根據評論編輯

可能想要在這里實現的一個非常簡單的重新表述如下。

由於您的 API 結果示例清楚地描述了一個包含對象的 object ,並且您的代碼似乎假定為一個數組,因此我不知道什么是真正正確的。 出於這個原因,渲染代碼只是轉儲加載的數據。

此外,缺少錯誤處理。

const SupplierData = () => {
  const [supplier, setSupplier] = React.useState(null);
  React.useEffect(() => {
    axios
      .get(`http://localhost:8080/api/suppliers/supplier/list`)
      .then((response) => setSupplier(response.data))
      .catch(alert);
  }, []);
  if (supplier === null) return <>Loading...</>;
  // TODO: implement better rendering code
  return <>{JSON.stringify(supplier)}</>;
};

export const A = (props) => {
  return (
    <>
      Hello, world!
      <SupplierData />
    </>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM