React this.context возвращает пустой объект {} в React Native 0.61 - PullRequest
0 голосов
/ 17 октября 2019

Я прочитал некоторые документы и ответы, связанные с этим, но не нашел конкретного ответа для моего случая. Я запускаю свой код как на React Native 0.61 (React версия 16.9.0), так и на игровой площадке Snack.

Проблема в том, что console.log(this.context) всегда возвращает пустой объект, подобный этому {}.

Код:

import React from 'react';
import { Text } from 'react-native';

const AppContext = React.createContext({})

class App extends React.Component {
  state = {
    products: [
      { id: 'p1', title: 'Gaming Mouse', price: 29.99 },
      { id: 'p2', title: 'Harry Potter 3', price: 9.99 },
    ],
    cart: []
  };

  render() {
    return (
      <AppContext.Provider
        value={{
          products: this.state.products
        }}
      >
      </AppContext.Provider>
    );
  }
}


export default class testScreen extends React.Component {
  static contextType = AppContext

  render() {
    console.log(this.context)

    return (
      <>
        <Text>{'Sometext'}</Text>
      </>
    );
  }
}

Ответы [ 2 ]

0 голосов
/ 17 октября 2019

Я решил проблему. Решение:

import React from 'react';
import { Text } from 'react-native';

const AppContext = React.createContext({})

class App extends React.Component {
  state = {
    products: [
      { id: 'p1', title: 'Gaming Mouse', price: 29.99 },
      { id: 'p2', title: 'Harry Potter 3', price: 9.99 },
    ],
    cart: []
  };

  render() {
    return (
      <AppContext.Provider
        value={{
          products: this.state
        }}
      >
        {this.props.children}
      </AppContext.Provider>
    );
  }
}

class TestScreen extends React.Component {
  static contextType = AppContext

  render() {
    console.log(this.context)

    return (
      <>
        <Text>{'Sometext'}</Text>
      </>
    );
  }
}

export default function AppComponent() {
 return <App><TestScreen/></App>
}
0 голосов
/ 17 октября 2019

Может быть

<AppContext.Provider
        value={{
          products: this.state.products
        }}
      >
      <testScreen/>
      </AppContext.Provider>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...