繁体   English   中英

使用 React Hook Forms 和 React Table 处理自定义组件

[英]Handle a custom component using React Hook Forms and React Table

我正在尝试为我的 react-hook-forms 和 react-table 设置一个自定义组件

const selectedUserIds =  watch(`user_ids`) || [];

<Controller
  control={control}
  name={fieldName("user_ids")}
  render={({ field: { value, onChange } }) => (
  <UserTable selectedUserIds={selectedUserIds} updatePropertySelection={onChange}/>
)}
/>

用户表:

function updatePropertyTableSelection(ids){
  const ids = extractIds(ids);
  updatePropertySelection(ids);
}

const selectedUserIdsForTable = convertIdsToTableFormat(selectedUserIds)
return (
<React.Fragment>
    <BasicTable
        tableHeader={() => null}
        columns={[
          {
            Header: "User Name",
            accessor: "attributes.name",
          }
        ]}
        data={data}
        selectedRows={selectedUserIdsForTable}
        onSelectedRowsChange={updatePropertyTableSelection}
      />
</React.Fragment>
)

当我将 onChange 处理程序关联到 updatePropertySelection 时,我陷入了无限的重新渲染。 我应该如何防止?

我遇到了同样的问题,我按照以下方法解决了这个问题:

  1. 第一个,我的问题来自旧的 react-hook-form,现在我使用^7.14.2及其解决问题。

  2. 第二个解决方案通过将onChange替换为field.onChange来解决问题,例如(来自真实项目):

     <Controller name={"explanation"} control={props.control} render={({field}) => { return ( <MyEditor placeholder={t("onlineAssessments.question.explanationPlaceholder")} onPressEnter={props.onPressEnter} onChange={(val, editor) => { // notify parent field.onChange(val); // calc count setExplanationCount(editor?.getBody().innerText.trim().length) } } /> ) } } />

我认为这个变化来自最新的更新..

  1. 可能你有一些保持重新渲染触发器,基于你的表,你可能需要useCallBackuseMemo来防止每次访问时重新渲染,如果依赖关系发生变化,例如:

     const updatePropertyTableSelection = useCallBack((ids) => { const ids = extractIds(ids); updatePropertySelection(ids); }, []);

    const selectedUserIdsForTable = useMemp(() => { convertIdsToTableFormat(selectedUserIds) }, []);

注意:不要忘记仅在需要时更新依赖项,并且仅更新您需要重新渲染的内容

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM