【问题标题】:React this.context returns empty object {} in React Native 0.61React this.context 在 React Native 0.61 中返回空对象 {}
【发布时间】:2020-02-14 03:34:53
【问题描述】:

我已经阅读了一些与此相关的文档和答案,但没有找到适合我的案例的具体答案。我在 React Native 0.61(React 版本 16.9.0)和 Snack playground 上运行我的代码。

问题是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>
      </>
    );
  }
}

【问题讨论】:

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


【解决方案1】:

也许

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 你会编辑这个答案来解释如何这解决了这个问题吗?如果答案得到解释,我认为未来的读者会从中学到更多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    相关资源
    最近更新 更多