使用redux-react集成copilot库报错:TypeError: Cannot read property 'getCurrentStep' of undefined
分析报错原因及解决方案
这个报错TypeError: Cannot read property 'getCurrentStep' of undefined的核心原因是:你放在navigationOptions里的<CopilotStep>无法获取到copilot高阶组件提供的上下文实例。
为什么会这样?因为navigationOptions是静态配置,它渲染的内容(headerRight里的组件)属于导航器的一部分,并不在被copilot()包裹的Abc组件的渲染树范围内,所以<CopilotStep>找不到copilot实例,自然调用getCurrentStep时就会报错。
另外,你的CustomComponent虽然接收了copilot props,但因为父级的<CopilotStep>没有正确连接到copilot上下文,这个props其实也是无效的。
具体修复步骤
1. 移除静态navigationOptions,动态设置headerRight
把headerRight的渲染逻辑移到componentDidMount或componentDidUpdate里,通过navigation.setParams动态设置,这样headerRight的组件会在Abc组件的上下文里渲染,就能拿到copilot的实例了。
2. 确保CopilotStep和子组件正确接收copilot上下文
修改后的代码示例:
const CustomComponent = ({ copilot, navigation }) => ( <View {...copilot}> <MaterialIcon name="add" size={30} color="white" style={{marginRight : 8}} onPress={() => { navigation.navigate("CreateSomething"); }} /> </View> ); class Abc extends React.Component{ componentDidMount(){ // 动态设置headerRight,确保组件在当前组件上下文内 this.props.navigation.setParams({ headerRight: this.renderHeaderRight() }); this.props.start(); } renderHeaderRight = () => { // 这里的CopilotStep能拿到copilot上下文,因为在组件的方法里渲染 return ( <View> <CopilotStep text="Click this icon to" order={1} name="addIcon"> <CustomComponent navigation={this.props.navigation} /> </CopilotStep> </View> ); } render() { return ( // 你的组件内容 <View>...</View> ); } } // 保留copilot HOC和connect的包裹顺序 const AbcWithCopilot = copilot({ verticalOffset: 26, animated: true, overlay: "svg" })(Abc); const exportedConnect = connect(mapStateToProps, mapDispatchToProps)(AbcWithCopilot); // 注意:现在不需要手动assign navigationOptions了,因为我们用动态设置的方式 export default exportedConnect;
额外注意点
- 确保
copilot高阶组件的包裹顺序正确:先包裹组件,再用connect连接redux,你的代码里顺序是对的(copilot()(Abc)然后connect(...)),这个没问题。 - 我在
CustomComponent里补充了navigationprops的传递,因为原来的代码里直接调用navigation.navigate会找不到navigation对象,你可以根据实际情况调整。
这样修改后,<CopilotStep>就能正确获取到copilot实例,getCurrentStep方法也就不会报undefined的错误了。
内容的提问来源于stack exchange,提问作者Neha
相关产品推荐
相关产品推荐

