我刚刚开始使用redux开发一个react native应用程序,我认为让登录屏幕正常工作的多种方法让我感到困惑。我的理解是,使用redux可以避免将props沿视图层次结构向下传递,而是使用可以使用>>> def values():
... yield 1 + 2 == 3
... print("Not reached by any()")
... yield 3 + 1 == 5
... print("Not reached by all()")
...
>>> any(values())
True
>>> all(values())
Not reached by any()
False
从中提取props
的存储。但是,每个组件都可以在mapStateToProps
中拥有自己的局部参数。我遇到的问题是,我似乎无法在Component中解开State
的包装,而我认为目前我在网上看到的不同设计模式之间感到困惑。
感谢您的时间
减速器
props
动作
export default(state = {}, action) => {
switch(action.type) {
case 'LOGIN':
return {
...state,
username: action.username,
}
case 'LOGIN_SUCCESS':
return {
...state,
jwt: action.payload.data
}
case 'LOGIN_FAIL':
console.log(action.payload.data);
return {
...state,
jwt: undefined,
}
default:
console.log('unhandled action')
return state
}
}
组件
return {
type: 'LOGIN',
username,
payload: {
request: {
url: '/api/token/obtain/',
method: 'POST',
data: {
username: username,
password: password,
}
}
}
}
}
父组件
import React, { Component, Fragment } from 'react';
import { Text, View } from 'react-native';
import { Input, TextLink, Loading, Button } from './common';
import { onLogin } from '../actions/auth.js'
import { connect } from 'react-redux';
class LoginComponent extends Component {
constructor(props) {
super(props);
this.state = {username: '', password: ''}; // Q2 How can I move the username to store and map to props using mapStateToProps?
}
render() {
console.log(this.props); // Q1 Why does this.props not have username, password and jwt?
return (
<Fragment>
<View>
<View>
<Input
placeholder="username"
label="Username"
value={this.state.username}
onChangeText={username => this.setState({ username })}
/>
</View>
<View>
<Input
secureTextEntry
placeholder="password"
label="Password"
value={this.state.password}
onChangeText={password => this.setState({ password })}
/>
</View>
<Text>
{error}
</Text>
{!loading ?
<Button onPress={() => this.props.onLogin(this.state.username, this.state.password)}>
Login
</Button>
:
<Loading size={'large'} />
}
</Fragment>
);
}
}
const mapStateToProps = state => {
return {
username: state.username,
password: state.password,
jwt: state.jwt,
}
};
const mapDispatchToProps = {
onLogin
};
export const Login = connect(mapStateToProps, mapDispatchToProps)(LoginComponent)
祖父母App.js
import React, { Component } from 'react';
import { View } from 'react-native';
import { Login } from '../components';
import { connect } from 'react-redux';
export default class Auth extends Component {
render() {
return(
<View>
<Login />
</View>
);
}
}