Reactjs 在React中绕过自定义挂钩的条件使用

Reactjs 在React中绕过自定义挂钩的条件使用,reactjs,react-hooks,Reactjs,React Hooks,使用React,我正在为一个插件编写代码,该插件根据调用它的应用程序使用本地存储或会话存储。它是通过向默认为本地存储的组件传递可选参数来设置的。如果我们的web服务正在使用插件,那么它会将会话存储方法传入。由于限制,我们的桌面应用程序不会传入参数,因此我们默认使用组件中的本地存储 export function myComponent(optionalParameter?: string, storeOptionalParameter?: (selection: string) => vo

使用React,我正在为一个插件编写代码,该插件根据调用它的应用程序使用本地存储或会话存储。它是通过向默认为本地存储的组件传递可选参数来设置的。如果我们的web服务正在使用插件,那么它会将会话存储方法传入。由于限制,我们的桌面应用程序不会传入参数,因此我们默认使用组件中的本地存储

export function myComponent(optionalParameter?: string, storeOptionalParameter?: (selection: string) => void) {
    const [variable, storeVariable] = optionalParameter && storeOptionalParameter
        ? [optionalParameter, storeOptionalParameter]
        : useLocalStorage<string>('storageName', 'default');
}
function Component({variable, storeVariable}) {
  ...
}

function ComponentThatUsesStore() {
  const [variable, storeVariable] = useLocalStorage<string>('storageName', 'default');
  return (<Component variable={variable} storeVariable={storeVariable} />)
}

function ParentComponent(...) {
   if (optionalParameter && storeOptionalParameter) {
     return (
       <Component
         variable={optionalParameter}
         storeVariable={storeOptionalParameter}
       />
     );
   }
   return <ComponentThatUsesStore />;
}
导出函数myComponent(optionalParameter?:string,storeOptionalParameter?:(选择:string)=>void){
常量[variable,storeVariable]=optionalParameter&&storeOptionalParameter
?[optionalParameter,storeOptionalParameter]
:useLocalStorage('storageName','default');
}

我知道这违反了钩子的规则。从技术上讲,它可以很好地编译和运行,因为每个渲染都取决于它所渲染的环境。我仍然想找到一个更好的方法来完成这项工作,这样我的衣帽匠就不会再抱怨了。

为什么不干脆把组件包起来呢

export function myComponent(optionalParameter?: string, storeOptionalParameter?: (selection: string) => void) {
    const [variable, storeVariable] = optionalParameter && storeOptionalParameter
        ? [optionalParameter, storeOptionalParameter]
        : useLocalStorage<string>('storageName', 'default');
}
function Component({variable, storeVariable}) {
  ...
}

function ComponentThatUsesStore() {
  const [variable, storeVariable] = useLocalStorage<string>('storageName', 'default');
  return (<Component variable={variable} storeVariable={storeVariable} />)
}

function ParentComponent(...) {
   if (optionalParameter && storeOptionalParameter) {
     return (
       <Component
         variable={optionalParameter}
         storeVariable={storeOptionalParameter}
       />
     );
   }
   return <ComponentThatUsesStore />;
}
函数组件({variable,storeVariable}){
...
}
使用存储()的函数组件{
const[variable,storeVariable]=useLocalStorage('storageName','default');
返回()
}
函数ParentComponent(…){
if(optionalParameter&&storeOptionalParameter){
返回(
);
}
返回;
}

我最终得到了类似的解决方案。组件从两个位置调用,其中一个位置已被包装。我可以调用每种存储类型,并根据需要将它们传递给每个组件。我本该早点看到的,但你的解决方案让我明白了。