簡體   English   中英

有條件地更新父類傳遞的事件處理程序中子組件的 state

[英]Conditionally updating child component's state in event-handler passed by Parent-class

const Child = (props) => {
  const [val, setVal] = useState(props.val);

  const handleCreate = (newData) => new Promise((resolve, reject) => {
        setTimeout(() => {
            {
                const transactions = JSON.parse(JSON.stringify(tableData));
                const clean_transaction = getCleanTransaction(newData);
                const db_transaction = convertToDbInterface(clean_transaction);
                transactions.push(clean_transaction);
// The below code makes post-request to 2 APIs synchronously and conditionally updates the child-state if calls are successful.
                **categoryPostRequest(clean_transaction)
                    .then(category_res => {
                        console.log('cat-add-res:', category_res);
                        transactionPostRequest(clean_transaction)
                            .then(transaction_res => {
                                addToast('Added successfully', { appearance: 'success'});
                                **setVal(transactions)**
                            }).catch(tr_err => {
                            addToast(tr_err.message, {appearance: 'error'});
                        })
                    }).catch(category_err => {
                    console.log(category_err);
                    addToast(category_err.message, {appearance: 'error'})
                });**
            }
            resolve()
        }, 1000)
    });

  return (
    <MaterialTable
            title={props.title}
            data={val}
            editable={{
                onRowAdd: handleCreate
            }}
        />
  );
}

const Parent = (props) => {
  // some other stuff to generate val
  return (
    <Child val={val}/>
  );
}

我正在努力實現這一點:我想將句柄創建(粗體部分)中 function 的請求后部分移到可由子類調用的父組件。 這個想法是使組件抽象並可由其他類似的父類重用。

在parent中創建function,並在props中傳給child:

const Parent = (props) => {
  // The handler
  const onCreate = /*...*/;

  // some other stuff
  return (
    <Child ...props onCreate={onCreate}/>
  );
}

然后讓孩子使用它需要的任何參數調用 function (您的示例中似乎沒有任何參數,例如,您沒有在其中使用val ):

return (
  <MaterialTable
          title={props.title}
          data={val}
          editable={{
              onRowAdd: props.onCreate // Or `onRowAdd: () => props.onCreate(parameters, go, here)`
          }}
      />
);

旁注:沒有理由將props.val復制到子組件中的val state 成員,只需使用props.val

旁注 2:解構通常對 props 很方便:

const Child = ({val, onCreate}) => {
  // ...
};

旁注 3:您的Parent組件通過...props調用Child及其所有道具:

return (
  <Child ...props onCreate={onCreate}/>
);

這通常不是最好的。 只傳遞Child它實際需要的東西,在這種情況下, valonCreate

return (
  <Child val={props.val} onCreate={onCreate}/>
);

暫無
暫無

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

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