简体   繁体   中英

React: Class Based Context API to Hook Based context API

I am really new in Hooks and during learning faces many difficulties to switch from the old style.

My old code looks like:

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>

but when I want to access it through with export default withContext(SomeComponent) by this.props.server.someFunc() it showed props is undefined in the classless hook function.

how can I achieve this.props in react hook

Edit:

SomeClass is not React inheriting class and its look like it.

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

SomeComponent

const SomeComponent = () => {
...

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

...
}

In the regular case, you need to export the Context, then import it and use it within useContext :

export const SomeContext = React.createContext(null);


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

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

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

But in your case, since you using HOC, you have the server within the prop it self:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM