Javascript 可以使用react钩子注入组件吗? 我想我有一组组件,这些组件都有一些基本字段。例如,在出现错误状态时显示的弹出窗口

Javascript 可以使用react钩子注入组件吗? 我想我有一组组件,这些组件都有一些基本字段。例如,在出现错误状态时显示的弹出窗口,javascript,reactjs,react-hooks,dry,Javascript,Reactjs,React Hooks,Dry,这会导致类似以下情况: function MyComponent(props) { const [showErr, setShowErr] = React.useState(false); const [errMsg, setErrMsg] = React.useState(''); return <> <...> <SomePopup open={showErr}

这会导致类似以下情况:

function MyComponent(props) {
    const [showErr, setShowErr] = React.useState(false);
    const [errMsg, setErrMsg] = React.useState('');
    return <>
        <...>
        <SomePopup
            open={showErr}
            errMsg={errMsg}
        />
    </>
}
功能MyComponent(道具){
const[shower,setShowErr]=React.useState(false);
const[errMsg,setErrMsg]=React.useState(“”);
返回
}
虽然这是微不足道的,但在与组件其余部分进行更复杂交互的情况下,设置可能不是。这也是不必要的样板和干巴巴的

当然,这些状态可以组合在一个定制的钩子
usererror
(或者在这个简单的情况下组合在一个状态中)。但是,我是否也可以这样做:每当我声明一个对象具有
useError
,它也会设置组件


这样,我可以防止ErrOS像“忘记弹出”和“忘记设置有用错误状态”——“干错误”。

< P>而不是钩子,请考虑下面的高阶组件定义:

function withSomePopup(MyComponent) {
  return function MyComponentWithSomePopup(props) {
    const [showErr, setShowErr] = React.useState(false);
    const [errMsg, setErrMsg] = React.useState('');
    const propsWithSomePopup = React.useMemo(() => ({
      ...props,
      setShowErr,
      setErrMsg
    }), [props, setShowErr, setErrMsg]);

    return (
      <>
        <MyComponent {...propsWithSomePopup} />
        <SomePopup open={showErr} errMsg={errMsg} />
      </>
    );
  };
}
带有somepopup(MyComponent)的函数{
返回函数MyComponentWithSomePopup(道具){
const[shower,setShowErr]=React.useState(false);
const[errMsg,setErrMsg]=React.useState(“”);
const propsWithSomePopup=React.useMoom(()=>({
…道具,
setShowErr,
塞特尔姆格
}),[props,setShowErr,setErrMsg]);
返回(
);
};
}
然后可以像这样包装组件:

export default withSomePopup(function MyComponent(props) {
  const { setShowErr, setErrMsg } = props;

  return (
    <...>
  );
});
export default with somepopup(函数MyComponent(props)){
const{setShowErr,setErrMsg}=props;
返回(
);
});

出于好奇,最好将其编写为HOC而不是hook,您是否希望每个组件都呈现自己的单独弹出实例,或者您更喜欢呈现一个弹出实例并在多个组件之间共享dispatchers
setShowErr
setErrMsg
的实现?@PatrickRoberts我自己也不确定自己的偏好。一方面,“错误状态消息”如果结合在一起就很好了。然而,另一方面,每个组件都有自己的弹出实例,这使得组件“自行”工作,因此更易于测试。这是公平的。如果您更喜欢共享实例,我只是想建议为弹出窗口实现一个上下文提供程序。不过,我现在有点想知道,
usemo
的原因是什么<代码>道具更改(对象标识)每种呈现方式是否正确?@paul23不一定。除了对
道具的引用
更改之外的其他事项也会触发组件的重新呈现,例如通过调用dispatchers
setShowErr
SetErrorMsg
来更改状态,并且将对
props
的引用回记将防止对
useEffect()
进行不必要的刷新。,依赖于传递给内部组件的
道具的。通常,这种优化会导致性能无法观察到的改善,但如果任何依赖性触发网络请求等效果,则记忆至关重要。