首页 > 解决方案 > 在父类传递的事件处理程序中有条件地更新子组件的状态

问题描述

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}/>
  );
}

我正在努力实现这一点:我想将handleCreate(粗体部分)中函数的请求后部分移到可由子类调用的父组件。这个想法是使组件抽象并可由其他类似的父类重用。

标签: javascriptreactjsuse-state

解决方案


Create the function in the parent, and pass it to the child in the props:

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

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

Then have the child call the function with any parameters it needs (there don't seem to be any in your example, you're not using val in it for instance):

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

Side note: There's no reason to copy props.val to val state member within the child component, just use props.val.

Side note 2: Destructuring is often handy with props:

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

Side note 3: You have your Parent component calling Child with all of its props, via ...props:

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

That's generally not best. Only pass Child what it actually needs, in this case, val and onCreate:

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

推荐阅读