【发布时间】:2020-08-14 04:10:13
【问题描述】:
在我的主要App.js 组件中,我正在尝试更新我的状态
const[isAuthenticated, setIsAuthenticated] = useState(false)
当我加载我的用户给定我在本地存储中的令牌时为真。
useEffect(() => {
const loadUser = async () => {
await fetch('http://localhost:5000/api/auth', {
method: 'GET',
headers: {
'x-auth-token': localStorage.token,
},
});
setIsAuthenticated(true);
};
loadUser();
}, []);
在我的回报中,我正在渲染一个私有组件......
<PrivateRoute exact path='/upload' component={Upload} isAuthenticated={isAuthenticated} />
我的PrivateRoute.js 文件看起来像这样...
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route
{...rest}
render={(props) =>
isAuthenticated ? <Component {...props} /> : <Redirect to='/login' />
}
/>
);
几乎通过将isAuthenticated 作为道具传递给我的PrivateRoute 组件,我认为isAuthenticated 应该更新为true。我通过检查从我提出的请求中返回的数据来检查我是否正确加载了用户,并且确实我得到了用户并且setIsAuthenticated 被调用
但是,当我在加载用户后尝试检查isAuthenticated 中的PrivateRoute 时,我得到isAuthenticated 是false
我不确定为什么会这样,非常感谢一些帮助和解释。
我的 App.js 文件如下所示...
const App = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
const loadUser = async () => {
await fetch('http://localhost:5000/api/auth', {
method: 'GET',
headers: {
'x-auth-token': localStorage.token,
},
});
localStorage.setItem('token', localStorage.token);
setIsAuthenticated(true);
};
loadUser();
}, []);
return (
<Router>
<div className='d-flex flex-row mb-5'>
<Menu />
<div className='d-flex flex-column mt-5 w-100'>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/login' component={SignIn} />
<PrivateRoute
exact
path='/upload'
component={Upload}
isAuthenticated={isAuthenticated}
/>
</Switch>
</div>
</div>
</Router>
);
};
【问题讨论】:
-
您能否包含渲染
PrivateRoute的组件的整个 组件代码?您是否在PrivateRoute中登录了一个效果挂钩isAuthenticated以查看它是否正在接收更新的状态?您可以提供哪些尝试调试的详细信息? -
在
PrivateRoute我控制台登录isAuthenticated看看它有什么价值。我还添加了我的 App.js 文件的外观 -
@MichaelTorres 你怎么知道 console.log 在获取用户后正在打印?或者你如何检查
isAuthenticated里面的PrivateRoute? -
“在 PrivateRoute 中,我在控制台记录了 isAuthenticated 以查看它有什么价值。” 那个值是什么?你看到它在
App的状态下更新了吗?当它在App中的状态发生变化时,你看到它更新了吗? -
应该,你确定 fetch 没有错误?如果 fetch 出错,setIsAuthenticated 将不会执行