`replaceState` 在 Promise 的 `then` 中不起作用
`replaceState` not working inside `then` of a Promise
假设我们有一个 API 调用对用户进行身份验证,然后根据是否从服务器返回用户,我们要么 replaceState 要么什么都不做,这可能看起来像这样:
<Route component={App} onEnter={authUser} />
const onEnter = (nextState, replaceState) => {
if (isClient) {
AuthHelper.findCurrentUser()
.then(response => {
// This here doesn't work, `replaceState` doesn't change the page or URL, however I know for sure
// that the line is being called because if I put a `debugger` right before it,
// the `debugger` hits every time...
replaceState({nextPathname: nextState.location.pathname}, '/dashboard');
})
.catch(response => {});
// If we put the same line here, it redirects the user to the dashbaord.
// replaceState({nextPathname: nextState.location.pathname}, '/dashboard');
}
}
replaceState 工作与不工作之间的唯一区别因素是,一个是在 Promise 的 then 内调用的,一个是在 Promise 决议之外调用的。 Promise 会影响 replaceState 的执行吗?
异步 onEnter
挂钩的语法必然有点不同,因为我们需要一种方法来阻止转换,直到处理程序完成 运行。
如果您的 onEnter
钩子是异步的,那么它需要接受第三个参数,例如
function onEnter(nextState, replaceState, callback) {
/* ... */
}
执行此操作时,您必须在输入挂钩完成后 callback()
自己调用 运行。我们有必要使用这个 API 来支持那些人,例如没有使用
假设我们有一个 API 调用对用户进行身份验证,然后根据是否从服务器返回用户,我们要么 replaceState 要么什么都不做,这可能看起来像这样:
<Route component={App} onEnter={authUser} />
const onEnter = (nextState, replaceState) => {
if (isClient) {
AuthHelper.findCurrentUser()
.then(response => {
// This here doesn't work, `replaceState` doesn't change the page or URL, however I know for sure
// that the line is being called because if I put a `debugger` right before it,
// the `debugger` hits every time...
replaceState({nextPathname: nextState.location.pathname}, '/dashboard');
})
.catch(response => {});
// If we put the same line here, it redirects the user to the dashbaord.
// replaceState({nextPathname: nextState.location.pathname}, '/dashboard');
}
}
replaceState 工作与不工作之间的唯一区别因素是,一个是在 Promise 的 then 内调用的,一个是在 Promise 决议之外调用的。 Promise 会影响 replaceState 的执行吗?
异步 onEnter
挂钩的语法必然有点不同,因为我们需要一种方法来阻止转换,直到处理程序完成 运行。
如果您的 onEnter
钩子是异步的,那么它需要接受第三个参数,例如
function onEnter(nextState, replaceState, callback) {
/* ... */
}
执行此操作时,您必须在输入挂钩完成后 callback()
自己调用 运行。我们有必要使用这个 API 来支持那些人,例如没有使用