ReactJS 和 Redux 中的初始身份验证检查

Initial authentication check in ReactJS and Redux

背景:我有一个显示电影列表的应用程序,但我想做的是只为授权用户显示列表(通过检查令牌存储在本地存储中)。

所以我要实现的流程是:

  1. 用户进入应用主页面
  2. 检查本地存储中是否有令牌
  3. 如果是检查是否授权
  4. 如果授权 = 显示列表,否则不显示

所以我现在所做的是在我创建我的商店后立即在我的主要(包装)组件中:

const store = configureStore();
var token = localStorage.get(authConstants.LOCAL_STORAGE_TOKEN_KEY);
if(token){
    store.dispatch(actions.checkInitialAuth(token));
}

checkInitialAuth 操作是:

export function checkInitialAuth(token){
    return dispatch => {
        dispatch(requestLogin());
        return fetch(authConstants.API_USER_DETAILS, {headers: { 'Authorization' : `Bearer ${token}`}})
            .then(function(response){
                if(!response.ok){
                    throw Error(response.statusText);
                }
                return response.json();
            })
            .then(function(user){
                localStorage.set(authConstants.LOCAL_STORAGE_TOKEN_KEY, token);
                dispatch(receiveLogin(user)); // <==========
                dispatch(setTopMovies()); // <==========
            })
            .catch(function(err){
                // TODO: handle errors
                console.log(err);
            });
    }
}

所以问题是,在创建商店之后和元素创建之前立即调用初始身份验证检查的位置是否正确?

现在,如果我必须仅在用户获得授权时调用更多操作,我是否必须在 then 中调用它们checkInitialAuth行动?它是发出所有动作调度调用的正确位置吗?

最后一个,当身份验证错误时(我手动将本地存储上的令牌更改为错误)console.log(err) 正在按预期进行记录,但我还有这个烦人的401 error in the console,我能以某种方式避免它吗?

非常感谢!

is it the right place to invoke the initial auth check right after the creating store and right before the element creation?

是的。通常这是在将存储传递给 Provider.

之前进行所有初始化的地方

is it the right place to make all the action dispatch calls?

这在很大程度上取决于您的应用程序逻辑。您的组件可以检查用户是否经过身份验证,以显示 'topMovies' 的正确内容。但没有什么能阻止您在这里发送更多操作。

but I have also this annoying 401 error in the console, can I somehow avoid it?

是网络请求错误。这是您的 fecth 正在联系的服务器的响应。如果你真的想隐藏它们,你可以通过更改 Chrome 开发控制台过滤器来隐藏错误(但为什么?)。