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

Кто-нибудь может просветить меня?


person Hanif Nr    schedule 29.04.2020    source источник


Ответы (1)


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;
  }
}
person Shubham Khatri    schedule 29.04.2020
comment
что, если бы нам пришлось использовать несколько контекстов? - person CarlosCarucce; 20.08.2020
comment
Также обратите внимание, что если вам нужен контекст внутри функции класса: this.context.fetchChatList({}); - person msmfsd; 21.08.2020
comment
@CarlosCarucce Для этого есть обходной путь здесь. - person Rubek Joshi; 21.09.2020
comment
для множественного контекста обратитесь к responsejs.org/docs/context.html#consuming-multiple -контексты - person Giorgi Gvimradze; 18.06.2021