【问题标题】:React: Class Based Context API to Hook Based context APIReact:基于类的上下文 API 到基于钩子的上下文 API
【发布时间】:2020-11-17 18:25:13
【问题描述】:

我是 Hooks 的新手,在学习过程中要从旧样式转换时遇到很多困难。

我的旧代码如下所示:

context.js

import React from "react";

const SomeContext = React.createContext(null);

export const withContext = (Component) => (props) => (
  <SomeContext.Consumer>
    {(server) => <Component {...props} server={server} />}
  </SomeContext.Consumer>
);

export default SomeContext;

main index.js

<SomeContext.Provider value={new SomeClass()}>
   <App />
</SomeContext.Provider>

但是当我想通过this.props.server.someFunc() 使用export default withContext(SomeComponent) 访问它时,它显示道具在无类挂钩函数中未定义。

如何在反应钩子中实现this.props

编辑:

SomeClass 不是 React 的继承类,看起来很像。

class SomeClass {
  someFunc = (id) => axios('api endpoints')
} 

一些组件

const SomeComponent = () => {
...

useEffect(() => {
   this.props.server.someFunc(id).then(...).catch(...)
}, ...)

...
}

【问题讨论】:

  • 应该是value={&lt;SomeClass/&gt;},你最好向我们展示代码,而不是描述你想做什么。见How to create a Minimal, Reproducible Example
  • SomeClass 是一个没有继承 react 的简单类。
  • 只显示代码...函数组件中没有this.props
  • 好的,我编辑主帖
  • 请查看 React 文档,这不是您使用 Context 的方式,请参阅 useContext

标签: javascript reactjs


【解决方案1】:

一般情况下,需要先导出Context,然后导入并在useContext内使用:

export const SomeContext = React.createContext(null);


// Usage
import { SomeContext } from '..';

const SomeComponent = () => {
  const server = useContext(SomeContext);

  useEffect(() => {
    server.someFunc(id);
  });
};

但在您的情况下,由于您使用 HOC,因此您在 prop 中拥有 server 它自己:

const SomeComponent = (props) => {
  useEffect(() => {
    props.server.someFunc(id);
  });
};

【讨论】:

    猜你喜欢
    • 2015-05-09
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2013-02-17
    • 2021-05-15
    • 1970-01-01
    • 2020-09-12
    相关资源
    最近更新 更多