gpt4 book ai didi

reactjs - 在 React/Redux 中更改异步操作完成时的路由

转载 作者:行者123 更新时间:2023-12-03 14:27:11 24 4
gpt4 key购买 nike

我正在使用 React、Redux 和 React-router。我有一个“添加成员”按钮,可以使用 react 路由器打开“新成员”表单。

在“应用程序容器”中,我有这个:

<Switch>
//other stuff
<Route exact path='/addmember' component={ NewMemberForm }/>
</Switch>

和按钮:

<Button label='Add member' onClick={ _ => this.props.history.push('/addmember')} />

表单已正确打开。 NewMemberForm 组件有两个按钮:AddCancelCancel 按钮基本上是 this.props.history.push('/') 返回主页。

当用户单击添加时,将读取表单数据并调度异步操作:

//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 };
};

当调度 ADD_MEMBER 操作时,即当实际上添加了新成员。

我什么时候必须处理该操作并调用 this.props.history.push('/')?在分派(dispatch)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 }))));
};

最佳答案

我找到了一个可行的解决方案。

history.js

import createHistory from 'history/createHashHistory'
export default createHistory()

在 Action 创建器中:

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 })))
});
};

关于reactjs - 在 React/Redux 中更改异步操作完成时的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49072742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com