對於React和Redux,我相對較新,並且我創建了一個簡單的ajax電子郵件表單來進行學習。我遇到的問題是,在表單提交後,我將商店狀態設置回初始狀態,它應清除所有字段,但不會。我可以看到商店在Redux記錄器中的更改,*請參閱附加的圖像,但這些更改未顯示在用戶界面上。我的商店沒有正確映射到狀態?或者我在某處變異狀態?在商店更改後,redux UI不會更新
我減速如下所示:
export default function contactForm(state = initialState.formValues, action) {
switch (action.type) {
case types.FORM_RESET:
return initialState.formValues;
case types.FORM_SUBMIT_SUCCESS:
return Object.assign({}, action.message);
default:
return state;
}
}
聯合減速器:
import { combineReducers } from 'redux';
import message from './formReducer';
import ajaxCallsInProgress from './ajaxStatusReducer';
const rootReducer = combineReducers({
message,
ajaxCallsInProgress
});
我的初始化狀態是這樣的:
export default {
formValues: {
name: '', email: '', message: '',
},
ajaxCallsInProgress: 0,
};
我的操作是這樣的:
export function messageSuccess(message) {
return { type: types.FORM_SUBMIT_SUCCESS, message };
}
export function resetForm() {
return { type: types.FORM_RESET };
}
export function saveMessage(message) {
return function (dispatch) {
dispatch(beginAjaxCall());
return messageApi.saveMessage(message)
.then(() => {
dispatch(messageSuccess(message));
dispatch(resetForm());
}).catch((error) => {
dispatch(ajaxCallError(error));
throw (error);
});
}
}
在我通過映射狀態道具的觀點:
constructor(props, context) {
super(props, context);
this.state = {
message: Object.assign({}, this.props.message),
}
}
render() {
return (
<ContactForm
onChange={this.updateMessageState}
onSubmit={this.submitForm}
message={this.state.message}
/>
);
}
function mapStateToProps(state) {
return {
message: state.message,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(formActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(ContactSection);
日誌顯示保存修改
我會很感激的任何建議。
你能提供你的初始狀態是什麼樣子嗎?我認爲問題的根源在於你在減速器中改變狀態。 – Tom
湯姆,我剛剛添加了初始狀態 –