我使用redux-forms来处理所有与表单相关的事情。但是redux-form和连接装饰器都不能很好地协同工作。当表单提交更改我的redux商店时,Connect正在更新我的showSpinner属性。但是下次当redux存储库发生变化时,我的连接属性不会更新。
以下是代码:
component.js
const formSubmit = (values, dispatch) => {
dispatch(submitLogin(values));
}
const mapStateToProps = (state, ownProps) => {
return {
app: state.app,
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
mockSubmit: values => {
dispatch(submitLogin(values));
}
}
}
@connect(mapStateToProps, mapDispatchToProps)
@reduxForm({form: 'loginForm', validate, onSubmit: formSubmit})
class Login extends Component {
constructor(props) {
super(props);
}
render() {
const fullWidth = true;
const self = this;
return (
<div>
<p>{self.props.app.showSpinner.toString()}</p>
<CircularProgress size={80} thickness={5} style={{display: self.props.app.showSpinner ? "block" : "none"}} />
<form onSubmit={this.props.handleSubmit}>
<div className="card-box">
<div className="head">
<p>Login</p>
</div>
<div className="body">
<Field name="phone" type="text" component="input" label="Mobile Number"/>
</div>
</div>
</form>
<Terms/>
</div>
)
}
}
export default Login;
action.js
export function submitLogin(data){
return dispatch => {
dispatch(fetchLoginApi(data));
fetchLogin(data) //a helper method to hit login api
.then(res => {
dispatch(verifiedUser(res));
})
.catch(err => console.log(err))
}
}
function fetchLoginApi(data) {
return{
type: SUBMIT_LOGIN,
data
}
}
function verifiedUser(data) {
return {
type: VERIFIED_USER,
data
}
}
app.js //在combine reducer中,我将此reducer添加为app
const initialState = {
showSpinner: false,
showAlert: false,
showConfirm: false,
}
export function app(state = initialState, action) {
switch(action.type) {
case SUBMIT_LOGIN:
return Object.assign(state, {
showSpinner: true
});
break;
case VERIFIED_USER:
return Object.assign(state, {
showSpinner: false
});
break;
default:
return state;
}
}
我正在使用thunk中间件。所有导入都以正确的方式完成,没有语法错误,我正在使用注释来装饰具有连接和reduxForm等HOC的类。
答案 0 :(得分:1)
您错误地实施了app
reducer。它会改变state
个对象而不是创建一个新对象。
应该是
export function app(state = initialState, action) {
switch(action.type) {
case SUBMIT_LOGIN:
return Object.assign({}, state, { // notice new object as the first arg
showSpinner: true
});
case VERIFIED_USER:
return Object.assign({}, state, {
showSpinner: false
});
default:
return state;
}
}