在React Native Redux中调度导入的函数
问题描述:
这是我第一次使用React Native,并且只使用Redux,但我的Redux/authentication.js
中有一个函数,该函数应该使用Firebase创建一个新帐户。在React Native Redux中调度导入的函数
export function handleAuthWithFirebase (newUser) {
return function (dispatch, getState) {
dispatch(authenticating());
console.log(newUser);
console.log('Signing up user');
var email = newUser.email;
var password = newUser.password;
firebase.auth().createUserWithEmailAndPassword(email, password).catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
}).then(() => {
var user = firebaseAuth.currentUser;
// Set user in Firebase
firebase.database().ref('/users/' + user.uid).set({
displayName: newUser.displayName,
userName: newUser.userName,
email: newUser.email
})
})
dispatch(isAuthed(user.uid))
}
}
我导入此功能为SignUpForm组件,获取用户信息,对一些<TextInput/>
的。所以现在我想运行handleSignUp
函数,但我不完全确定如何。
class SignUpForm extends Component {
static propTypes = {
}
state = {
email: '',
password: '',
username: '',
displayName: ''
}
handleSignUp() {
// Want to call handleAuthWithFirebase(this.state) here.
}
render() {
console.log(this.props);
return (
<View style={{flex: 1}}>
<View>
<TextInput
style={styles.input}
onChangeText={(email) => this.setState({email})}
value={this.state.email}
autoCorrect={false}
/>
<TextInput
style={styles.input}
onChangeText={(password) => this.setState({password})}
value={this.state.password}
autoCorrect={false}
/>
<TextInput
style={styles.input}
onChangeText={(username) => this.setState({username})}
value={this.state.username}
autoCorrect={false}
/>
<TextInput
style={styles.input}
onChangeText={(displayName) => this.setState({displayName})}
value={this.state.displayName}
autoCorrect={false}
/>
</View>
<View>
<Button title="Sign Up" onPress={this.handleSignUp}>Sign Up</Button>
</View>
</View>
)
}
}
export default connect()(SignUpForm)
它显示我dispatch
可作为道具,当我console.log(this.props)
,但是当我尝试在handleSignUp
方法做this.props.dispatch(handleAuthWithFirebase(this.state))
我得到道具的错误undefined
答
这是因为你的回调有一个自己的范围,因为它是一个命名函数。只需将它绑定在你的按钮,像这样:
<Button title="Sign Up" onPress={this.handleSignUp.bind(this)}>Sign Up</Button>
这样做的原因是,从不同的上下文中调用时,除非你明确的功能结合到一定this
功能范围的变化。你需要这些才能访问道具。除此之外,你的代码看起来很好,但是如果你在解决问题时遇到麻烦,请告诉我。
答
当您将组件连接到商店时dispatch
将作为道具传递给您的组件。
在你handleSignUp
你可以做到以下几点: -
handleSignUp() {
const {dispatch} = this.props
//input validations
const newUser = this.state
dispatch(handleAuthWithFirebase(newUser))
}
也为您的按钮,你需要绑定this
。这个你可以在按钮做
<Button title="Sign Up" onPress={this.handleSignUp.bind(this)}>Sign Up</Button>
或在构造
constructor(){
super()
this.this.handleSignUp = this.handleSignUp.bind(this)
}