[英]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.我真的是 Hooks 的新手,在学习过程中面临许多从旧风格转换的困难。
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.但是当我想访问它通过与export default withContext(SomeComponent)
由this.props.server.someFunc()
这表明道具无类钩子函数是不确定的。
how can I achieve this.props
in react hook我怎样才能在反应钩子中实现this.props
Edit:编辑:
SomeClass is not React inheriting class and its look like it. SomeClass 不是 React 继承类,它看起来像它。
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
:在常规情况下,您需要导出 Context,然后导入它并在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:但是在您的情况下,由于您使用 HOC,因此您在prop
拥有server
:
const SomeComponent = (props) => {
useEffect(() => {
props.server.someFunc(id);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.