我是React Native的新手,当我尝试构建一个平面列表时,我遇到了一个问题,当按下列表项时,该列表导航到具有项目详细信息的另一个屏幕。我正在使用redux和react-native-router-flux在屏幕之间导航。平面列表正在渲染,但是当我按下项目时,我无法导航到另一个屏幕。
这是我的代码:
class MyListItem extends React.PureComponent {
_onPress = () => {
this.props.onPressItem(this.props.item);
};
render() {
return (
<TouchableOpacity
{...this.props}
onPress={this._onPress}>
<View style={styles.GridViewContainer} >
<Text style={styles.GridViewTextLayout} >{this.props.item.name}</Text>
</View>
</TouchableOpacity>
);
}
}
class CustomersList extends Component {
componentWillMount() {
this.props.getCustomers();
}
componentDidUpdate(prevProps) {
if (prevProps.customers !== this.props.customers) {
this.props.getCustomers();
}
}
_keyExtractor = (item, index) => item._id;
_onPressItem = (item) => {
Actions.customerShow({ customer: item });
};
_renderItem = ({ item }) => (
<MyListItem
id={item._id}
item={item}
onPressItem={() => this._onPressItem(item)}
title={item.name}
/>
);
render = () => {
return (
<View style={styles.container}>
<FlatList
data={this.props.customers}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
extraData={this.state}
numColumns={3}
/>
</View>
);
}
}
const mapStateToProps = (state) => {
const customers = state.customers;
console.log(customers);
debugger
return { customers };
};
export default connect(mapStateToProps, {
getCustomers
})(CustomersList);
这是axios api:
export const getCustomers = () => {
debugger;
return (dispatch) => {
dispatch(setCustomerLoading)
axios
.get('https://calm-sands-26165.herokuapp.com/api/customers')
.then(res =>
dispatch({
type: GET_CUSTOMERS,
payload: res.data,
})
)
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: null
})
);
};
}
路由栈:
const RouterComponent = () => {
return (
<Router >
<Scene key="root" hideNavBar>
<Scene key="auth">
<Scene key="login" component={LoginForm} title="Please Login" initial />
</Scene>
<Scene key="main">
<Scene
onRight={() => Actions.customerCreate()}
rightTitle="Add"
key="customersList"
component={CustomersList}
title="Customers"
initial
/>
<Scene key="customerCreate" component={CustomerCreate} title="Create Customer" />
<Scene key="customerShow" component={CustomerShow} title="Show Customer" />
</Scene>
</Scene>
</Router>
);
};
提前致谢,
当FlatList
提供的数据源不是数组时,会导致错误。在您的情况下,this.props.customers
未定义,直到返回函数this.props.getCustomers()
。
我建议使用状态来渲染CustomersList
组件中的平面列表。并且当从axios异步调用this.setState({customers : nextProps.customers})
返回结果时更新状态,该调用将使用customers数组重新呈现FlatList
。
class CustomersList extends Component {
constructor(props){
super(props);
this.state = {
customers : []
};
}
...
render = () => {
return (
<View style={{flex:1}}>
{this.state.customers.length > 0 ?
<FlatList
data={this.state.customers}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
extraData={this.state}
numColumns={1}
/> :
<View style={styles.container}>
<ActivityIndicator size={'large'}/>
</View>
}
</View>
);
}
}
至于你的导航,我自己测试了你的代码并且它工作了:)(正如你所看到的,当列表仍在获取时我使用<ActivityIndicator />
进行渲染。