使用React Hook Forms和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}/>
)}
/>

UserTable:

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. 首先,我的问题来自旧的反应钩子形式,现在我使用^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)
    }, []);
    

注意:不要忘记只在需要时更新依赖项,并且只更新到重新渲染

所需的依赖项。