簡體   English   中英

在反應js中保留antd select中的選定選項

[英]persist selected option in antd select in react js

我正在開發一個 reactjs 項目,其中我使用 antd select 組件來顯示公司列表。

選擇任何公司名稱將顯示以該公司名稱注冊的用戶。 在這里,附加的視頻是可以啟用/禁用公司的 root 用戶。

To enable/disable company, I am using antd switch which will call API and toggle the company state and when company state is changed, I need to again call the getCustomers API which will give me list of companies as company's state is rendered based on response來自 API。

Here, issue is that suppose I am selecting one option from select and toggles its state then get customers API will be called again and so first company will be the selected option in select component. 每當切換任何公司的 state 時,我都想更改它,然后切換后應選擇同一家公司。

有關更多說明,請參閱隨附的視頻。 最初,當在選項中選擇 Trace_Client_1 時,當我單擊 TestOrg1 並切換其 state 然后在切換 TestOrg1 后應該選擇而不是 Trace_Client_1。

我知道這是因為 state 渲染而發生的,但不知道如何解決它。

看視頻

 useEffect(() => {
    const selectedCustomer = selectedCustomer
      ? selectedCustomer
      : customers[0] || {};

    fetchUsers(selectedCustomer.companyName);
    fetchLocations(selectedCustomer.companyName);
    setSelectedCustomer(selectedCustomer);
  }, [customers]);

 const toggleOrganizationVisiblity = async () => {
    const { message, res } = await Data.toggleOrganizationVisiblity(
      selectedCustomer?.companyName
    );

    if (res?.status === 401) {
      signout();
    }

    await fetchCustomers();
    DisplaySuccessMessage({ obj: { message } });
  };

const onChange = async (id) => {
    const selectedCustomer =
      customers.filter((customer) => customer.id === id)[0] || {};

    await fetchUsers(selectedCustomer.companyName);
    await fetchLocations(selectedCustomer.companyName);
    setSelectedCustomer(selectedCustomer);
  };

  return <>
     <CustomersList
        customers={customers}
        onChange={onChange}
        selectedCustomer={selectedCustomer}
      />
    <Switch
        checked={!selectedCustomer?.isCompanyDisabled}
        onChange={toggleOrganizationVisiblity}
        style={{ textAlign: 'right' }}
    />
    <Table
        size="small"
        style={{ marginTop: '10px' }}
        bordered
        dataSource={users}
        rowClassName={selectedCustomer?.isCompanyDisabled && 'disabled-row'}
        columns={columns}
    />
</>

請幫助我,因為我自過去 2 天以來一直陷入困境。

在 useEffect 中,您可以嘗試將selectedCustomer重命名為selectedCustomerReference並嘗試切換公司

 useEffect(() => {
    const selectedCustomerReference = selectedCustomer
      ? selectedCustomer
      : customers[0] || {};

    fetchUsers(selectedCustomerReference.companyName);
    fetchLocations(selectedCustomerReference.companyName);
    setSelectedCustomer(selectedCustomerReference);
  }, [customers]);

暫無
暫無

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

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