我收到错误
类型错误:无法读取未定义的属性“导航”。我不明白如何将导航组件传递给每个子组件,因此当用户按下某个项目时,它可以使用 React Navigation 导航到 employeeEdit 组件。我是新手,如果这是显而易见的,我很抱歉。
import React, { Component } from 'react';
import { FlatList } from 'react-native';
import { connect } from 'react-redux';
//import { R } from 'ramda';
import _ from 'lodash';
import { employeesFetch } from '../actions';
import { HeaderButton } from './common';
import ListEmployee from './ListEmployee';
class EmployeeList extends Component {
static navigationOptions = ({ navigation }) => ({
headerRight: (
<HeaderButton onPress={() => navigation.navigate('employeeCreate')}>
Add
</HeaderButton>
)
});
componentWillMount() {
this.props.employeesFetch();
}
keyExtractor(item) {
return item.uid;
}
renderItem({ item }) {
return <ListEmployee employee={item} navigation={this.props.navigation} />;
}
render() {
return (
<FlatList
data={this.props.employees}
renderItem={this.renderItem} // Only for test
keyExtractor={this.keyExtractor}
navigation={this.props.navigation}
/>
);
}
}
const mapStateToProps = (state) => {
const employees = _.map(state.employees, (val, uid) => ({ ...val, uid }));
return { employees };
};
export default connect(mapStateToProps, { employeesFetch })(EmployeeList);
这是 ListEmployee 的代码
import React, { Component } from 'react';
import {
Text,
StyleSheet,
TouchableWithoutFeedback,
View
} from 'react-native';
import { CardSection } from './common';
class ListEmployee extends Component {
render() {
const { employee } = this.props;
const { navigate } = this.props.navigation;
const { textStyle } = styles;
const { name } = this.props.employee;
return (
<TouchableWithoutFeedback onPress={() => navigate('employeeEdit', { employee })}>
<View>
<CardSection>
<Text style={textStyle}>{name}</Text>
</CardSection>
</View>
</TouchableWithoutFeedback>
);
}
}
/**
second argument in connect does 2 things. 1. dispatches all actions creators
return action objects to the store to be used by reducers; 2. creates props
of action creators to be used by components
**/
export default ListEmployee;
const styles = StyleSheet.create({
textStyle: {
fontSize: 18,
paddingLeft: 15,
}
});
这是 ES6 常见的陷阱之一。别担心我的朋友,你只需学习一次就可以再次避免它们。
长话短说,当你在 React Component 中声明一个方法时,将其设置为箭头函数
所以,要从这个开始改变。
renderItem({ item }) {
to this
renderItem = ({ item }) => {
这应该可以解决您的问题,由于某些不方便的原因,如果您将方法声明为箭头函数,则只能访问“this”,但不能使用普通声明。
在您的情况下,由于 renderItem 不是箭头函数,因此“this”不引用反应组件,因此“this.props”可能是未定义的,这就是它给您这个错误的原因Cannot read property 'navigation' of undefined
since
this.props.navigation = (undefined).navigation
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)