React:首先调用onChange钩子,同时设置defaultChecked

问题描述 投票:0回答:1

let radio_onchange = (e) => {
    variable.radio = radio_name;
    if (on_update) on_update();
};

let radio_defaultChecked = variable_index === radio_index;

return (
    <Fragment key={radio_index}>        <input type='radio'               name={radio_id + '-' + radio_name}
               value={radio_name}
               defaultChecked={radio_defaultChecked}
               onChange={radio_onchange}
        />    </Fragment>);


更改时,单选按钮有一个副作用,即将variable.radio设置为radio_name。

现在defaultChecked仅设置最初对无线电进行检查,即组件首次安装时。 我还想在 onchange 最初加载的那一刻触发它的副作用。

我可以使用类似 useEffect 的东西,没有依赖项,但是上面的代码有两个循环深(迭代 n 个变量和 k 个无线电),所以当我在 radio_defaultChecked 下面使用 useEffect 来调用 radio_onchange 时,会抛出一些错误,比如

Warning: React has detected a change in the order of Hooks called by VariableForm. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks

解决这个问题的最佳方法是什么?将每个(变量、单选)元组提取到其自己的组件中,该组件使用 useEffect 仅初始设置variable.radio?

javascript reactjs react-hooks
1个回答
0
投票

我为您看到了 2 个选择:

  • 找到一种方法在组件根部的全局
    useEffect
    中进行所有调用。这对我来说是最干净的方式。
  • 如果你真的不能,你可以将
    input
    以及循环内的所有逻辑提取到专用组件中,这样它就可以拥有自己的
    useEffect
© www.soinside.com 2019 - 2024. All rights reserved.