reactjs - React - 类内的useContext
问题描述
我是新手,我想在课堂上使用 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;
}
}
推荐阅读
- javascript - 在 symfony 中添加 CollectionType 表单时如何保持 Javascript 功能
- pytorch - 训练 OpenAI 点唱机上采样器时,损失值会在一段时间后变得疯狂
- xamarin.forms - 列表视图无法显示来自 Cloud Firestore 的数据
- sql-server - 在 MS SQL 中匿名销售和其他数据
- phpspreadsheet - 更改通过 getCellByColumnAndRow 获得值的单元格的颜色
- css - CSS 和 Bootstrap - 我已经用示例中的 bootstrap 3 完成了方形线 css,但与 bootstrap 4 线相同的 css 消失了吗?
- node.js - Nodejs中多个API调用的套接字挂断错误
- highcharts - Highcharts - 指标数据未显示在折线图中
- azure - 具有多个 BOT 集成的 Microsoft Chat BOT
- apache-kafka - 新的 Kafka 消费者忽略最早的偏移量