Update at the bottom of post
我有一个React容器组件 AppContainer
,它检测用户是否经过身份验证 . 如果用户已通过身份验证,则会显示路由,应用程序, Headers 等 . 如果用户未经过身份验证,则会显示“登录”组件 .
AppContainer
是一个连接组件(使用react-redux) . mapStateToProps
和 mapDispatchToProps
如下:
const mapStateToProps = function(state) {
return {
isAuthenticated: state.Login.isAuthenticated,
}
}
const mapDispatchToProps = function(dispatch, ownProps) {
return {
loginSuccess: (user) => {
console.log("before dispatch")
dispatch(loginSuccess(user))
},
}
}
正在调度的 loginSuccess
函数是一个动作创建器,它只是将用户信息存储在redux存储中 . 默认状态 Login.isAuthenticated
为false .
在 componentDidMount()
中,我检查 this.props.isAuthenticated
(来自redux商店中的用户信息)是否为真 . 如果没有,我检查 tokenId
是否在localStorage中 . 如果令牌在localStorage中,我会调度 loginSuccess
操作以将该信息添加到redux存储 .
然后,由于该信息位于Redux存储中,因此该组件将更新并显示受保护的材料 . 这很好用 .
我的 componentDidMount
功能如下:
componentDidMount() {
if (this.props.isAuthenticated) {
console.log("REDUX AUTH'D")
} else {
if (localStorage.getItem("isAuthenticated") && !this.props.isAuthenticated) {
console.log("BROWSER AUTHD, fire redux action")
this.props.loginSuccess({
profileObj: localStorage.getItem("profileObj"),
tokenObj: localStorage.getItem("tokenObj"),
tokenId: localStorage.getItem("tokenId"),
})
}
}
}
唯一的问题是我收到以下警告:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the t component.
虽然给出的错误表明setState()存在问题,但我没有在整个程序中的任何地方调用setState(),所以......但是删除componentDidMount中的 this.props.loginSuccess({ ...
也会删除错误 .
我的代码中的 log
语句在错误之前打印,如果auth存在,组件会按预期呈现受保护的信息 . 如果组件似乎正在工作,为什么会出现此错误?
Update:
查看堆栈跟踪显示它来自我正在使用的google-login实用程序 .
这是该组件的代码:https://github.com/anthonyjgrove/react-google-login/blob/master/src/google.js
1 回答
这是NPM包提供的
google-login
React组件的问题 . 我通过基于Redux状态中的isAuthenticated值有条件地(在其自己的容器组件中,未在原始问题中显示)呈现google-login
组件来修复此问题 .