Redirect Redux中间件中重定向的实现
假设我有以下行动:Redirect Redux中间件中重定向的实现,redirect,reactjs,redux,react-router-redux,Redirect,Reactjs,Redux,React Router Redux,假设我有以下行动: export function signIn(data) { return { type: USER_SIGN_IN, promise: api.post('/sign_in', data) } } 以及以下中间件: export default function promiseMiddleware() { return next => action => { const { promise, type, ...rest }
export function signIn(data) {
return {
type: USER_SIGN_IN,
promise: api.post('/sign_in', data)
}
}
以及以下中间件:
export default function promiseMiddleware() {
return next => action => {
const { promise, type, ...rest } = action
if (!promise) {
return next(action)
}
const SUCCESS = `${type}_SUCCESS`
const REQUEST = `${type}_REQUEST`
const ERROR = `${type}_ERROR`
next({ type: REQUEST, ...rest })
return promise
.then(res => {
next({ response: res.data, type: SUCCESS, ...rest })
return true
})
.catch(error => {
...
})
}
}
此代码松散地基于
但是如果在中调用next
后调用回调,我想重定向到另一个路径怎么办?
我没有跟随。我通过操作传递了重定向url:
export function signIn(data) {
return {
type: USER_SIGN_IN,
promise: api.post('/sign_in', data),
redirect: '/'
}
}
并从react router redux
添加了另一个调用next
方法的push
import { push } from 'react-router-redux'
export default function promiseMiddleware() {
return next => action => {
const { promise, type, redirect, ...rest } = action
...
return promise
.then(res => {
next({ response: res.data, type: SUCCESS, ...rest })
next(push(redirect))
return true
})
.catch(error => {
...
})
}
}
这似乎是可行的,但我不确定这是否是一个好主意,或者是否存在多个next
调用的陷阱,我不应该这样做
也许有更好的方法来实现这样的重定向?似乎还可以,但你最好将你的问题复制粘贴到yes,复制到codereview,并添加一个链接,我认为你可以用
redux thunk
@webdeb做得更好谢谢,我在那里创建了一个问题-似乎还可以,但是你最好将你的问题复制粘贴到yes,复制到codereview,并添加一个链接,我认为你可以使用redux thunk
@webdeb做得更好谢谢,我在那里创建了一个问题-