我正在使用React,Redux和react-router。我有一个按钮"添加会员"这会打开一个新成员"形式,使用react-router。
在" app容器"中,我有:
<Switch>
//other stuff
<Route exact path='/addmember' component={ NewMemberForm }/>
</Switch>
和按钮:
<Button label='Add member' onClick={ _ => this.props.history.push('/addmember')} />
表格正确打开。 NewMemberForm
组件有两个按钮:Add
和Cancel
。基本上,Cancel
按钮会this.props.history.push('/')
返回主页。
当用户点击Add
时,会读取表单数据并调度异步操作:
//add member using the api and set the generated ID
export const requestAddMember = member => dispatch => {
return api.addMember(member)
.then(memberId => dispatch(
addMember(Object.assign(member, { id: memberId }))));
};
const addMember = member => {
return { type: ADD_MEMBER, member };
};
当调度this.props.history.push('/')
操作时,即实际添加新成员时,我需要返回主页(ADD_MEMBER
)。
我何时必须处理该操作并致电this.props.history.push('/')
?它应该在发送ADD_MEMBER
之前在异步操作创建者中吗?
//add member using the api and set the generated ID
export const requestAddMember = member => dispatch => {
return api.addMember(member)
.then(memberId => dispatch( // should it be here before this dispatching?
addMember(Object.assign(member, { id: memberId }))));
};
答案 0 :(得分:0)
我找到了一个有效的解决方案。
<强> history.js 强>
import createHistory from 'history/createHashHistory'
export default createHistory()
并在动作创建者中:
<强> actions.js 强>
import history from './history';
...
//add member using the api and set the generated ID
export const requestAddMember = member => dispatch => {
return api.addMember(member)
.then(memberId => {
history.push('/'); //this line
dispatch(addMember(Object.assign(member, { id: memberId })))
});
};