【发布时间】:2018-11-30 05:41:41
【问题描述】:
我有一个使用 react 和 redux 开发的组件。现在我想使用 recompose,但我不明白将它与 redux 一起使用的有组织的方式。通过有组织的方式,我的意思是说,在我以前有两个函数,如 mapStateToProps 和 mapDispatchToProps 并且它们被包裹在 connect HOC 中,这使我认为代码看起来更具可读性和简洁性。我的问题是我如何像我为 redux 部分所做的那样做同样的事情?我在搜索这种方式时找不到,所以我不确定是否有办法,如果有人可以通过分享来帮助我,好吗?
这是我的代码
import React from 'react';
import { connect } from 'react-redux';
const mapStateToProps = state => ({
loginData: state.loginData,
});
const mapDispatchToProps = dispatch => ({
login: user => dispatch(login(user)),
});
class Login extends React.Component<{ login: Function }> {
state = {
error: false,
user: {
email: '',
password: '',
},
};
handleChange = (e) => {
const { name, value } = e.target;
this.setState({ user: { ...this.state.user, [name]: value } });
};
handleSubmit = (e) => {
e.preventDefault();
this.props.login(this.state.user);
};
renderError() {
if (this.state.error) {
return (
<ErrorMessage>
The following email is not associated with us. Please create an
account to use our service
</ErrorMessage>
);
}
return <div />;
}
render() {
const { user } = this.state;
return (
<WhitePart>
<UpperPart>
<TitleContainer>
<TitleText>Login</TitleText>
</TitleContainer>
{this.renderError()}
<Form>
<form onSubmit={this.handleSubmit}>
<StyledField
label="Email"
id="email"
name="email"
type="text"
value={user.email}
placeholder="Email"
className="input-field"
component={GTextField}
onChange={this.handleChange}
style={{
marginBottom: '20px',
}}
required
fullWidth
/>
<StyledField
label="Password"
id="password"
name="password"
type="password"
value={user.password}
placeholder="Password"
className="input-field"
component={GPasswordField}
onChange={this.handleChange}
required
fullWidth
/>
<ButtonContainer>
<PrimaryButton
type="submit"
style={{
textTransform: 'none',
fontFamily: 'Lato',
fontWeight: 300,
}}
>
Login
</PrimaryButton>
</ButtonContainer>
</form>
</Form>
</UpperPart>
</WhitePart>
);
}
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Login);
对于 handleChange 和 handleSubmit 我可以使用 withHandler 和 withState 但对于 mapStateToProps 和 mapDispatchToProps 我不熟悉。
【问题讨论】:
-
你想组织哪一部分?
-
recmpose 中的 mapStateToProps 和 mapDispatchToProps。
标签: javascript reactjs redux recompose