我是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)
  }
...
}

谁能启发我吗?

推荐答案

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;
  }
}

React-native相关问答推荐

AxiosError:Reaction Native EXPO开发版本中的网络错误

Redux toolkit通过按钮操作进行查询

如何在Reaction本地日历中 Select 年份?

React本机组件未更新状态

React-Native:请纠正我对状态如何工作的误解 - 动态文本输入

导航堆栈不显示

在 React Native 中使用 Flatlist scrollView 时的模式关闭

React Native - 何时调用componentWillUnmount?

如何在 Recompose 中使用 withHandlers 将 refs 添加到功能组件并在 ScrollView 上调用 ScrollTo?

React Native 白色黑屏问题

我可以在状态内有一个函数来响应吗?

如何在 React-Native 中创建检测自动位置的map

'React native run android' 在模拟器中启动应用程序后立即停止

react-native alignSelf 中心并拉伸到 maxWidth?

因 JVM 堆空间耗尽而导致守护进程到期?

React-Native Android 中隐藏(hide)的元素溢出

React Native - Firebase 身份验证持久性不起作用

React Native EXPO Apple 上传失败

在 webview 中检测touch 是 Apple Pencil 还是手指(react-native)

/bin/sh: adb: 找不到命令