我目前正在构建松弛克隆。我想检查用户是否在每次安装组件时都已经登录,如果要先将其推送到主页,否则将其推送到登录页面。我使用react钩子而不是componentDidMount
进行检查,还使用mapDispatchToProps
来重新存储用户的登录状态。
我收到警告
import React,{useEffect} from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import Login from './components/Auth/login'
import Register from './components/Auth/register'
import reportWebVitals from './reportWebVitals';
import {BrowserRouter as Router,Switch,Route,useHistory,withRouter} from 'react-router-dom'
import 'semantic-ui-css/semantic.min.css'
import firebase from './firebase'
import { createStore } from 'redux'
import { Provider,connect} from 'react-redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import rootReducer from './reducers/index';
import * as actions from './actions/index';
import Spinner from './spinner'
const store=createStore(rootReducer,composeWithDevTools())
const Root=(props)=>{
const history=useHistory()
useEffect(() => {
console.log("1")
firebase.auth().onAuthStateChanged(user=>{
if(user){
props.setUser(user);
history.push('/home')
}
else{
history.push('/login')
props.clearUser();
}
})
},[history.location.hash,history])
return props.isLoading ? <Spinner/>:(
<Switch>
<Route exact path="/home" component={App} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
</Switch>
)
}
const mapStateToProps=state=>{
return {
isLoading:state.user.isLoading,
user:state.user.currentuser
}}
const mapDispatchToProps=dispatch=>{
return{
setUser:(user)=>dispatch(actions.SETuser(user)),
clearUser:()=>dispatch(actions.CLEARuser())
}
}
const RootwithAuth=withRouter(connect(mapStateToProps,mapDispatchToProps)(Root))
ReactDOM.render(
<Provider store={store}>
<Router>
<RootwithAuth/>
</Router>
</Provider>,
document.getElementById('root')
);
reportWebVitals();
答案 0 :(得分:1)
您需要传递props
作为依赖项。如果您有很多props
,可能会导致性能下降。最好是destructure
您的道具并通过依赖项数组。
在您的情况下,将是这样:
const {setUser, clearUser} = props;
useEffect(() => {
console.log("1")
firebase.auth().onAuthStateChanged(user=>{
if(user){
setUser(user);
history.push('/home')
}
else{
history.push('/login')
clearUser();
}
})
},[history.location.hash,setUser,clearUser])
这是警告要说的
答案 1 :(得分:1)
这是eslint-plugin-react-hooks警告。
告诉您钩子取决于useEffect中的函数调用
您可以使用代码/* eslint-disable react-hooks/exhaustive-deps */
的注释顶部来告诉ESLint忽略对钩子的检查。