javascript - 在新屏幕上评估 redux 操作(this.props.function)时“未定义不是对象”
问题描述
我有一个带有三个选项卡的应用程序(使用 react-navigation v2)。在一个选项卡上,我有一个名为“设置”的按钮,通过以下方式将用户引导至设置屏幕。
<Button
transparent
danger
onPress={() => this.props.navigation.navigate('Settings')}
>
<Text>Settings</Text>
</Button>
如果我使用该应用程序并单击不同的屏幕,则不会发生错误,并且可以很好地导航到设置屏幕。但是,如果我刚刚重新加载应用程序,导航到相应的选项卡并单击设置按钮,我会收到以下错误:
错误中引用的方法 (this.props.fetchAdminSettings) 是我试图导航到的 SettingsScreen 类中的方法。SettingsScreen 类的相关代码如下所示。
import {
fetchAdminSettings,
logout
} from '../../actions';
class SettingsScreen extends Component {
static navigationOptions = {
title: 'Settings',
headerStyle: {
backgroundColor: '#ff0000',
},
headerTintColor: '#fff'
};
componentDidMount() {
this.willFocusSubscription = this.props.navigation.addListener('willFocus', this.willFocus);
}
componentWillUnmount() {
if (this.willFocusSubscription) {
this.willFocusSubscription.remove();
}
}
willFocus() {
this.props.fetchAdminSettings(this.props.organization);
}
.
.
[some render methods]
.
.
render() {
return (
<Container>
<Content>
<View style={{ backgroundColor: 'white', flex: 1 }}>
<View style={{ flex: 1, marginTop: 50 }}>
<Text style={{ fontColor: 'red', fontSize: 10 }}>
{this.props.errorMessage}
</Text>
{this.renderAdminSettings(this.props.admin)}
{this.renderUserSettings()}
</View>
</View>
</Content>
</Container>
);
}
}
const mapStateToProps = (state) => {
const { organization, rank, firstName, lastName, admin } = state.auth;
const { loadingAdminSettings,
securityCode,
totalBrotherhoods,
totalChapters,
totalCommunityService,
totalDues,
totalMixers,
errorMessage
} = state.settings;
return ({
organization,
rank,
firstName,
lastName,
admin,
loadingAdminSettings,
securityCode,
totalBrotherhoods,
totalChapters,
totalCommunityService,
totalDues,
totalMixers,
errorMessage
});
};
export default connect(mapStateToProps, {
fetchAdminSettings,
logout
})(SettingsScreen);
编辑 fetchAdminSettings 动作创建者如下:
export const fetchAdminSettings = (organization) => {
return (dispatch) => {
dispatch({ type: FETCH_ADMIN_SETTINGS });
firebase.database().ref(`${organization}/admin`)
.on('value', snapshot => {
dispatch({ type: FETCH_ADMIN_SETTINGS_SUCCESS, payload: snapshot.val() });
});
};
};
您能给我的任何帮助将不胜感激!
解决方案
解决它!
我不完全确定为什么,但我用来在 Focus 上重新渲染屏幕的代码(如下所示)是问题的根源。
相反,我自己在 componentWillMount() 中运行了 'fetchAdminSettings' 函数并且它起作用了。
componentDidMount() {
this.willFocusSubscription = this.props.navigation.addListener('willFocus', this.willFocus);
}
componentWillUnmount() {
if (this.willFocusSubscription) {
this.willFocusSubscription.remove();
}
}
willFocus() {
this.props.fetchAdminSettings(this.props.organization);
}
推荐阅读
- pandas - 使用未排序时间序列滚动的熊猫
- node.js - 删除实体上的多对多关系表如何清除
- django - 更改网站语言的正确方法?
- unity3d - 尽管 vuforia-ball 是 imageTarget 的子级并且未检测到目标,但 vuforia-ball 不断下降
- vb6 - 如何在 vb6 中添加元标记?
- oracle - SQLPLUS破竖条中的特殊字符
- c# - 我需要“transactionScope.Complete();”吗?
- apache - Symfony 在登录后下载 Apache 服务器
- c - 创建我自己的外壳。处理 Ctrl-Z 然后发送 SIGCONT 会关闭进程而不是继续它
- r - 一键多值列展开[tidyr]