当用户访问网站时,我想在localStorage中检查jwtToken,如果它有效,用户将被重定向到主页。
但是ContainerComponent在解码令牌和设置要存储的数据之前会接收道具(带有isLoggedIn道具(。我能以某种方式修复它吗?
下面是我的检查令牌代码:
index.js
document.addEventListener("DOMContentLoaded", async () => {
const token = localStorage.getItem("jwtToken");
const store = configureStore();
//Check for token
if (token) {
// Set auth token header auth
API.setAuthToken(token);
// Decode token and get user info and exp
const decoded = await jwt_decode(token);
// Check for expired token
const currentTime = Date.now() / 1000;
if (decoded.exp < currentTime) {
// Logout user
await store.dispatch(logoutUser());
// Redirect to login
window.location.href = "/auth";
} else {
await store.dispatch(setCurrentUser(token));
}
}
ReactDOM.render(
<Router>
<Provider store={store}>
<App />
</Provider>
</Router>,
document.getElementById("root")
);
});
setCurrentUser操作如下:
// Logged in
export const authUser = (userData) => (dispatch) =>
API.auth(userData).then(
(res) => {
const token = res.data;
localStorage.setItem("jwtToken", token);
API.setAuthToken(token);
const decoded = jwt.verify(token, "Secret");
dispatch(receiveCurrentUser(decoded));
},
(err) =>
dispatch({
type: GET_ERRORS,
payload: err.response.data,
})
);
// Check login
export const authSuccess = (token) => (dispatch) => {
if (token) {
API.setAuthToken(token);
const decoded = jwt.verify(token, "Secret");
console.log("decoded", decoded);
dispatch(setCurrentUser(decoded));
} else {
dispatch(logoutCurrentUser());
}
};
// Set logged in user
export const setCurrentUser = (decoded) => {
return {
type: RECEIVE_CURRENT_USER,
payload: decoded,
};
};
// Session reducer
const _nullUser = Object.freeze({
id: null,
});
const sessionReducer = (state = _nullUser, action) => {
switch (action.type) {
case RECEIVE_CURRENT_USER:
return {
...state,
username: action.payload.username,
id: action.payload._id,
email: action.payload.email,
position: action.payload.position,
};
case LOGOUT_CURRENT_USER:
return _nullUser;
default:
return state;
}
};
export default sessionReducer;
我检查页面容器组件中的isLoggedIn
import AuthPage from "./authPage";
import { authSuccess } from "../../actions/session.actions";
import { authUser } from "../../actions/session.actions";
class AuthPageContainer extends React.Component {
render() {
return (
<>
<AuthPage
authSuccess={this.props.authSuccess}
authUser={this.props.authUser}
isLoggedIn={this.props.isLoggedIn}
/>
</>
);
}
}
const mapStateToProps = (state) => {
return {
isLoggedIn: Boolean(state.Session),
};
};
export default connect(mapStateToProps, { authUser, authSuccess })(
AuthPageContainer
);
我解决了那个问题!我不是调度thunk函数,而是调度普通对象
之前:store.dispatch(setCurrentUser(token))
之后:store.dispatch(authSuccess(token))