【发布时间】: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>
</>
);
}
}
【问题讨论】:
-
请阅读Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers? - 总结是这不是解决志愿者的理想方式,并且可能会适得其反。请不要将此添加到您的问题中。
标签: reactjs react-native react-context react-state-management