我希望在firebase auth管理器说没有经过身份验证的用户之后,从我的componentWillMount()调用一个操作。这是我的代码:
import React, { Component } from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import { Button } from 'react-native-elements';
import { Actions } from 'react-native-router-flux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import * as actions from '../actions';
import * as firebase from 'firebase';
import { responsiveHeight, responsiveWidth, responsiveFontSize } from 'react-native-responsive-dimensions';
const ristImage = require('../assets/risto-landing.png');
class LandingScreen extends Component {
componentWillMount(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log('User Logged-in')
} else {
console.log('No Authenticated User')
return(
this.props.dispatch(clearState())
)
}
});
}
fbLoginPress() {
this.props.fbLogin();
}
render() {
return (
<View style={styles.containerStyle}>
<View>
<Image
resizeMode="contain"
style={styles.landingImageStyle}
source={ristImage}
/>
<Text style={styles.titleAppStyle}>Risto </Text>
</View>
<View style={styles.buttonContainer}>
<Button
large
title="Sign in With Facebook"
backgroundColor="#4068AD"
icon={{ name: 'facebook-square', type: 'font-awesome' }}
style={[styles.buttonStyle, styles.fbColor]}
onPress={this.fbLoginPress.bind(this)}
/>
<Button
large
title="Sign In or Sign Up With Email"
icon={{ name: 'envelope', type: 'font-awesome' }}
backgroundColor="#F8A443"
style={[styles.buttonStyle, styles.emailColor]}
onPress={Actions.emailLogin}
/>
</View>
</View>
);
}
}
export default connect(null, actions)(LandingScreen);
现在,我想要的是从我的./authAction文件调用我的动作clearState()来清除初始状态。我的方法是正确的还是可以直接在我的componentWillMount中调用调度操作?
然后这就是我的clearState()在actions / js中的功能:
export const clearState = () => async (dispatch) => {
dispatch({type: SIGN_OUT});
console.log('State re-initialized');
}
答案 0 :(得分:1)
您提供给this
的回调中的onAuthStateChanged()
并非您认为的那样。它被绑定到没有名为props
的属性的其他东西。这就是你得到那个错误的原因。你可以做两件事来避免这种情况:
<强> 1。使用箭头功能:
firebase.auth().onAuthStateChanged(user => {
...
}
<强> 2。将回调绑定到this
。
firebase.auth().onAuthStateChanged((function(user) {
...
}).bind(this);
我更喜欢第一种选择。
此外,如果您将操作对象传递给connect()
函数,则不会将dispatch
注入您的道具中。相反,它将提供一个具有相同名称且已经包含在dispatch()
中的道具的功能。
[mapDispatchToProps(dispatch,[ownProps]):dispatchProps](对象或函数):如果传递了一个对象,则假定其中的每个函数都是一个Redux动作创建者。具有相同函数名称的对象,但每个动作创建者都包含在一个调度调用中,因此可以直接调用它们,它们将合并到组件的道具中。
这意味着您只需致电this.props.clearState()
。