我在理解使用 React Context API 的新方法时遇到了一些困难。 我有一个带有自定义类 Firebase 的应用程序。现在我想做一个钩子(Hook)来传递它。在我使用之前 HOC (高阶组件) 和上下文。
我的问题
- 我需要使用 HOC 还是一种新方法?
- 我需要 Context.Provider 还是它的新 Hook?
- 我需要将默认值声明为 null 还是我可以传递我的对象 直接来自 context.js
- 如何在我的代码中使用新的 Hook 而不是 HOC?
这是我的代码,带有一些与问题相关的注释
// context.js this is my hoc
// index.jsx
import App from './App'
import Firebase, { FirebaseContext } from './components/Firebase'
const FirebaseContext = React.createContext(null)
export const withFirebase = Component => (props) => {
// I don't need to wrap it to the FirebaseContext.Consumer
// 1 But do I need this HOC or it's a new way?
const firebase = useContext(FirebaseContext)
return <Component {...props} firebase={firebase} />
}
ReactDOM.render(
// 2 Here I'm lost. Do I need the FirebaseContext.Provider or not?
// 3 Do I need to declare value her or I should do it in context.js as a default?
<FirebaseContext.Provider value={new Firebase()}>
<App />
</FirebaseContext.Provider>,
document.getElementById('root'),
)
// App.jsx
// 4 Can I use a new Hook instead of HOC here and how?
import { withFirebase } from './components/Firebase/context'
const App = () => {
const firebase = this.props.firebase // But should be useContext(FirebaseContext) or something like this?
return(...)
}
export default withFirebase(App) // I don't need this with the Hook
感谢任何帮助。
最佳答案
你首先要明白,useContext
只是为了利用Context,它是一个消费者而不是提供者。
回答你的问题
Do I need to use HOC or it's a new way to do this?
您不需要带钩子(Hook)的 HOC。 Hooks 旨在取代 HOC 并渲染 props 模式。
Do I need the Context.Provider or it's new Hook?
没有与 Context.Provider 等效的 Hook 。您必须按原样使用它。
Do I need to declare default value as a null or I can pass my Object right from context.js
仅当您未将 value
属性传递给 Context.Provider
时,才会使用 createContext 的默认值。如果您传递它,默认值将被忽略。
How can I use a new Hook instead of HOC in mine code?
不要在 HOC 返回的组件中使用 useContext
,而是直接在组件中使用它
示例代码
/ context.js this is my hoc
// index.jsx
import App from './App'
import Firebase, { FirebaseContext } from './components/Firebase'
const FirebaseContext = React.createContext(null)
ReactDOM.render(
<FirebaseContext.Provider value={new Firebase()}>
<App />
</FirebaseContext.Provider>,
document.getElementById('root'),
)
App.jsx
const App = () => {
const firebase = useContext(FirebaseContext)
return(...)
}
export default App;
关于javascript - 使用新的 React hook useContext 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54758769/