首页 > 解决方案 > Dispatching logout from outside of a React Component

问题描述

I have a doubt with react-redux

I'm making an app that involves authentication, and from my server, if the auth fails I send back an error.

I made a function specifically for protected fetching, what i'd like is, if there's an error on the response, dispatch an action to log the user out, however this function isn't inside a react component and i've been told exporting the store isn't a good practice, so what's the right way to do this?

标签: reactjsreduxreact-redux

解决方案


Once you get the error you should probably report it somehow back to your component. You could have it as part of of your store... sometimes people use bool value, sometimes error text. In any way that error has to make back to your component. Your component will check for error (as you use redux, you will probably bind store's error value to a component's property. As an effect, inside of your component you will evaluate the value and call a redux action to log user out. The action will change store parameters, clean local storage, it can even call async server actions to log out on server side (see how redux-thunk and similar middleware works).


推荐阅读