使用 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. 根据你的table,你可能有一些保持重新渲染的触发器,你可能需要useCallBackuseMemo来防止重新渲染如果依赖项发生变化,则每次访问 else,例如:

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

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

注意:不要忘记仅在需要时更新依赖关系,并且仅更新您需要重新呈现的内容