Redux-Saga如何在Saga中调用localStorage.clear方法

TTC*_*TCG 2 javascript reactjs redux-saga

我正在尝试清除 Redux Saga 方法中存储在 localStorage 中的所有项目。但它没有按预期工作。

理论上,如果我想在Saga中调用一个函数,我们需要在没有括号的情况下使用call关键字来编写它。

所以,我尝试用它来编写它,yield call(localStorage.clear);但它并没有从本地存储中清除项目。如果我添加brackets ()或不添加yeild & call,它会按预期工作并清除 LocalStorage 中的项目。

export function* logoutUserSaga() {
try {
    const accessToken = yield call(AuthService.getAccessToken);
    yield call(AuthService.logoutUser, accessToken); 
    yield put(logoutUser.success());

    yield call(localStorage.clear); // not working

    //yield call(localStorage.clear()); // working
    //localStorage.clear(); // working

    yield put({ type: RESET_ALL_STATE });
}
catch (error) {
    yield put(logoutUser.failure({ errorMessage: error.statusText }));
}
}

export default function* watcherSaga() {
    yield takeLatest(authenticateUser.TRIGGER, authenticateUserSaga);
    yield takeLatest(logoutUser.TRIGGER, logoutUserSaga);
    yield takeLatest(getAccessToken.TRIGGER, getAccessTokenSaga);
}
Run Code Online (Sandbox Code Playgroud)

我想知道为什么没有括号()的调用函数不起作用。

是因为被调用的函数是void并且没有返回任何值吗?
如果我们想调用 void 方法,是否总是需要添加括号?

Nic*_*wer 7

它不起作用的原因是该localStorage.clear函数期望this等于localStorage。当使用 notation 时,这种情况会自动发生localStorage.clear,但如果您只有对该函数的引用并在没有上下文的情况下调用它,则会出现非法调用错误。这与传奇没有直接关系,可以像这样重现:

  const clear = localStorage.clear;
  clear(); // throws an exception
Run Code Online (Sandbox Code Playgroud)

不过,这确实与传奇有间接关系,这就是call工作方式。如果你没有告诉 call 在调用该函数时应该使用什么上下文,那么它别无选择,只能在全局上下文中调用它,从而导致此异常。call它的参数确实有一些变化,可以让您指定this应该相等的内容。例如,您可以这样做:

yield call([localStorage, localStorage.clear]);
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看调用接受的参数的其他变体:https ://redux-saga.js.org/docs/api/


另一种选择是不使用call. 使用 call 在尝试测试 saga 时有好处,并且它可以与 saga 和普通函数一起使用,但如果需要,您仍然可以自己调用普通函数。