React this.context在React Native 0.61中返回空对象{}

时间:2019-10-17 09:02:34

标签: reactjs react-native react-context react-state-management

我已经阅读了一些与此相关的文档和答案,但没有找到适合我的情况的具体答案。我在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 :(得分:0)

也许

<AppContext.Provider
        value={{
          products: this.state.products
        }}
      >
      <testScreen/>
      </AppContext.Provider>

答案 1 :(得分:0)

我解决了这个问题。解决方法是:

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