【问题标题】:How to abstract multiple similar function components (providers) in React?React中如何抽象出多个功能相似的组件(provider)?
【发布时间】:2023-01-12 12:04:55
【问题描述】:

我在 React 应用程序中有多个 providers / contexts 执行相同的操作,即调用 Nestjs 应用程序的 CRUD 操作:

export const CompaniesProvider = ({children}: {children: any}) => {
  const [companies, setCompanies] = useState([])

  const fetchCompany = async () => {
    // etc.
    try {
      // etc.
      setCompanies(responseData)
    } catch (error) {}
  }

  const updateCompany = async () => {
    // etc.
    try {
      // etc.
    } catch (error) {}
  }

  // same for delete, findOne etc..

  return (
    <CompaniesContext.Provider value={{ 
      companies, 
      saveSCompany, 
    }}>
      {children}
    </CompaniesContext.Provider>
  )
}

export const useCompanies = () => useContext(CompaniesContext)

另一个供应商,例如,技术模型看起来完全一样,它只是改变了 api url:

export const TechnologiesProvider = ({children}: {children: any}) => {
  const [technologies, setTechnologies] = useState([])

  const fetchTechnology = async () => {
    // etc.
    try {
      // etc.
      setTechnologies(responseData)
    } catch (error) {}
  }

  const updateTechnology = async () => {
    // etc.
    try {
      // etc.
    } catch (error) {}
  }

  // same for delete, findOne etc..

  return (
     <TechnologiesContext.Provider value={{ 
       technologies, 
       savesTechnology, 
     }}>
        {children}
     </TechnologiesContext.Provider>
  )
}

export const useTechnologies = () => useContext(TechnologiesContext)

重构的最佳方法是什么?我想要一个实现所有方法的抽象类,不同的模型提供者继承这些方法,抽象类只需要构造函数中的 api url..

但是 React 更喜欢函数组件,这样我们就可以像 useState 一样使用 hooks。

我应该将功能组件更改为类组件以便能够重构吗?但是后来我失去了钩子功能,这不是现在的反应方式。

另一个想法是将抽象类注入到功能组件中,而提供者只调用方法。

有任何想法吗?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    实现它的一种方法是创建一个工厂函数,该函数获取 url(以及其他需要的参数)并返回 providerconsumer

    这是此类功能的示例:

    export const contextFactory = (url: string) => {
      const Context = React.createContext([]); // you can also get the default value from the fn parameters
    
      const Provider = ({ children }: { children: any }) => {
        const [data, setData] = useState([]);
    
        const fetch = async () => {
          // here you can use the url to fetch the data
          try {
            // etc.
            setData(responseData);
          } catch (error) {}
        };
    
        const update = async () => {
          // etc.
          try {
            // etc.
          } catch (error) {}
        };
    
        // same for delete, findOne etc..
    
        return (
          <Context.Provider
            value={{
              data,
              save
            }}
          >
            {children}
          </Context.Provider>
        );
      };
    
      const hook = () => useContext(Context)
    
      return [Provider, hook]
    };
    

    这就是您如何创建新的提供者和消费者

    const [CompaniesProvider, useCompanies] = contextFactory('http://...')
    const [TechnologiesProvider, useTechnologies] = contextFactory('http://...')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-05
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 2020-05-30
      • 1970-01-01
      • 2021-04-08
      相关资源
      最近更新 更多