React Native集成DialogFlow报错:undefined is not an object (evaluating 'this.props = props')
解决React Native集成DialogFlow时的
undefined is not an object错误 嘿,我来帮你拆解这个问题并一步步修正它!
核心错误原因
你遇到的undefined is not an object (evaluating 'this.props = props')错误,根源在于类继承的写法错误:
// 错误写法:多了括号,Component是类,不能直接调用 class App extends Component() { // 正确写法:直接继承Component类本身 class App extends Component {
当你给Component加上括号时,相当于试图调用这个类(但Component是React的类,调用它会返回undefined),导致你的App类继承了undefined,进而在constructor里执行super(props)时,无法正确初始化this,触发了这个错误。
其他需要修正的问题
除了核心错误,代码里还有几处需要调整的地方:
- DialogFlow实例引用错误:你不需要从
this.props里获取dialogflow,因为已经直接导入了Dialogflow_V2模块,直接使用导入的对象即可。 - Button组件缺少必填属性:React Native的Button组件必须指定
title属性,否则会抛出错误。 - 私钥字符串语法错误:你的私钥字符串结尾多了一个多余的双引号,需要移除。
修正后的完整代码
import React, { Component } from 'react'; import { StyleSheet, View, Button } from 'react-native'; import { Dialogflow_V2 } from "react-native-dialogflow"; // 移除Component后的括号 class App extends Component { constructor(props) { super(props); Dialogflow_V2.setConfiguration( "sample.iam.gserviceaccount.com", // 移除结尾多余的双引号 '-----BEGIN PRIVATE KEY-----\sample\n-----END PRIVATE KEY-----\n', Dialogflow_V2.LANG_ENGLISH, 'sample-44ce3' ); } render() { return ( <View style={styles.container}> {/* 添加Button的title属性,直接使用Dialogflow_V2发起请求 */} <Button title="测试DialogFlow" onPress={() => { Dialogflow_V2.requestQuery( "hello", result => console.log(result), error => console.log(error) ); }} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, }); export default App;
验证修正效果
- 确保你的DialogFlow服务账号密钥、项目ID等信息正确无误。
- 重新运行项目,点击按钮后应该能正常向DialogFlow发起请求,并在控制台打印结果或错误信息。
内容的提问来源于stack exchange,提问作者Ramesh Raghavan
相关产品推荐
相关产品推荐

