【发布时间】:2018-04-13 21:24:30
【问题描述】:
总结
- 我创建了一个自定义 HOC,通过检查 redux 存储是否具有 user.id 属性来检查用户是否经过身份验证
- 我正在使用反应导航和反应原生
- 当我将屏幕组件包装到 HOC 中时,导航标题会出现但被空白(相反,如果我不将屏幕组件包装到 HOC 中,导航标题会正确显示)
- 在 HOC 和被包装的组件中也有 react-redux 连接,我想知道这是否会让事情崩溃
当我将屏幕组件包装在自定义 HOC 中时,为什么我的反应导航标题没有正确显示?
我想知道我是否以错误的顺序包装东西——这些是屏幕组件中可能有问题的代码行(在我测试时,其中一个被注释掉了):
// export default connect(mapStateToProps, mapDispatchToProps)(EntityPage); <--this renders the header fine
export default connect(mapStateToProps, mapDispatchToProps)(withAuthentication(EntityPage)); <--this renders the header blank
代码
我做的自定义 HOC 检查身份验证
import React, {
Component
} from 'react';
import PropTypes from 'prop-types';
import {
Alert
} from 'react-native';
import {
connect
} from 'react-redux';
function withAuthentication(Comp) {
class AuthenticatedScreen extends Component {
componentDidUpdate(prevProps) {
if (this.props.user && !this.props.user.id) {
Alert.alert('you\'re not logged in anymore');
}
}
render() {
return <Comp { ...this.props
}
/>;
}
}
function mapStateToProps(state) {
return {
user: state.user,
};
}
AuthenticatedScreen.propTypes = {
user: PropTypes.object,
component: PropTypes.object,
};
return connect(mapStateToProps)(AuthenticatedScreen);
}
export default withAuthentication;
我用自定义身份验证 HOC 包装的屏幕组件
import withAuthentication from '../User/AuthorizedHOC'; <--my custom HOC import
class EntityPage extends Component {
static navigationOptions = ({navigation}) => {
return {
title: 'My Entities',
headerRight: (
>> <Button type='action' title='Add New Entity' onPress={()=>navigation.navigate('EntityCreate')}>
</Button>),
headerStyle: {paddingRight: (Platform.OS === 'ios') ? 0 : 8},
};
};
componentDidMount() {
this.props.loadEntities();
}
render() {
const {
entities,
} = this.props;
return (
<FullscreenView>
<EntityList entities={entities}/>
</FullscreenView>
);
}
}
function mapStateToProps(state) {
return {
entities: getSortedEntityList(state),
};
}
function mapDispatchToProps(dispatch) {
return {
loadEntities: () => dispatch(loadEntities()),
deleteEntity: (entity) => dispatch(deleteEntity(entity)),
};
}
// export default connect(mapStateToProps, mapDispatchToProps)(EntityPage); <--this renders the header fine
export default connect(mapStateToProps, mapDispatchToProps)(withAuthentication(EntityPage)); <--this renders the header blank
【问题讨论】:
标签: reactjs react-native stack react-navigation