React Native类组件用Context API报错:_provider.default.Consumer未定义
解决React Native Context API的TypeError: undefined is not an object evaluating '_provider.default.Consumer'错误
看起来你在使用Context API的时候踩了几个常见的小坑,我来帮你一步步解决:
错误原因分析
你遇到的这个错误,本质是因为你导入的对象不对,并且用错了Consumer的来源。你的provider.js里导出的是MyContext(Context对象)和MyProvider(Provider类组件),但你在AddPhoto里错误地默认导入了一个叫Provider的东西,这个东西根本不是Context对象,自然没有Consumer属性。
具体修复步骤
1. 修正导入语句
在addPhoto.js里,把原来的导入代码:
import Provider from "../../../provider";
改成:
import { MyContext } from "../../../provider";
因为你需要的是Context对象(MyContext)来获取它的Consumer,而不是直接导入MyProvider组件。
2. 正确使用Consumer
把<Provider.Consumer>改成<MyContext.Consumer>,因为Consumer是属于Context对象的属性,不是MyProvider类组件的属性:
// 错误写法 <Provider.Consumer> // 正确写法 <MyContext.Consumer>
3. 修正Consumer的回调函数写法
你现在的回调函数写法(context = () => (...))是错误的,Consumer的子元素必须是一个接收context参数的函数,直接返回JSX即可:
<MyContext.Consumer> {context => ( <View style={styles.conatiner}> <View style={styles.authIocn}> <SimpleLineIcons name="camera" size={wp("30%")} /> </View> <View style={styles.header}> <Text style={styles.headerText}>Add Profile Photo</Text> </View> <View style={styles.paragraph}> <Text style={styles.paragraphText}> Add a profile photo so your friends know its you. </Text> </View> <Button block style={styles.button} onPress={this._pickImage}> <Text style={styles.buttonText}>Add a Photo</Text> </Button> <View style={styles.skipButtonView}> {/* 这里可以调用context里的changeAuthState方法 */} <TouchableOpacity onPress={() => context.changeAuthState(true)}> <Text style={styles.skipButtonText}>Skip</Text> </TouchableOpacity> </View> </View> )} </MyContext.Consumer>
4. 确保根组件被MyProvider包裹
最后要确认你的整个应用(或者AddPhoto的父组件)已经被MyProvider包裹,否则Consumer无法获取到Context的值:
比如在你的根组件(比如App.js)里:
import { MyProvider } from './provider'; import AddPhoto from './path/to/addPhoto'; export default class App extends React.Component { render() { return ( <MyProvider> {/* 这里可以放你的导航栈或者其他组件 */} <AddPhoto /> </MyProvider> ); } }
额外小提示
你在MyProvider里定义的changeAuthState方法目前是固定把isAuthenticated设为true,如果需要动态传值的话,可以改成:
changeAuthState: (value) => this.setState({ isAuthenticated: value })
这样更灵活。
内容的提问来源于stack exchange,提问作者prog
相关产品推荐
相关产品推荐

