我是React的新手,我想在我的课程中使用useContext,如何解决此问题?这是我当前代码的示例
import { Context } from '../context/ChatListContext'
const ChatList = ({ onAction }) => {
const {state, fetchChatList} = useContext(Context)
我希望我的课程也能做到
import { Context } from '../context/ChatListContext'
class MainScreen extends Component {
//const {state, fetchChatList} = useContext(Context) *how do i declare this?
constructor(props) {
super(props)
this.state = { loading: true, showAction: false }
setTimeout(() => {
StatusBar.setBackgroundColor(primary)
}, 100)
}
...
}
有人可以启发我吗?
答案 0 :(得分:9)
useContext
是一个不能在类组件中使用的钩子。为类组件定义一个static contextType
import { Context } from '../context/ChatListContext'
class MainScreen extends Component {
static contextType = Context
constructor(props) {
super(props)
this.state = { loading: true, showAction: false }
setTimeout(() => {
StatusBar.setBackgroundColor(primary)
}, 100)
}
...
render() {
const {state, fetchChatList} =this.context;
}
}