【发布时间】:2020-09-10 00:54:50
【问题描述】:
我在我的项目中使用 aws-amplify、react-hook。该应用程序有一些私有路由已定义如下:
const ProtectedRoute = ({render: C, props: childProps, ...rest}) => {
return (
<Route
{...rest}
render={rProps =>
(childProps) ? (
<C {...rProps} {...childProps} />
) : (
<Redirect
to={`/login?redirect=${rProps.location.pathname}${
rProps.location.search
}`}
/>
)
}
/>
);
}
在 App.js 中,我们改变 childProps 来定义用户是否登录。但是当 childProps 改变时,Switch 不会重新渲染。什么是强制 React 重新渲染其 Route 的方法,因为 isAuthenticated 是更改但 ProtectedRoute 不是重新渲染。
const [isAuthenticated, userHasAuthenticated] = useState(null);
useEffect(() => {
onLoad();
}, []);
async function onLoad() {
try {
let user = await Auth.currentSession();
if (user.accessToken.payload) {
userHasAuthenticated(user.accessToken.payload);
}
} catch (e) {
if (e !== 'No current user') {
alert(e);
}
}
}
.....
const childProps = isAuthenticated;
return (
<ApolloProvider client={client} >
<div className="App">
<BrowserRouter>
<Route path='/'>
<div>
<Switch>
<Route path='/login' render={props => <Login {...props}/>} exact/>
<ProtectedRoute
exact
path='/admin/:name'
render={()=> <Admin />}
props={childProps}
/>
<Route path='/' render={props => <User {...props} />}/>
</Switch>
</div>
</Route>
</BrowserRouter>
</div>
</ApolloProvider>)
【问题讨论】:
-
你在哪里检查
childProps的值来改变做什么? -
对不起。我上传旧代码。 childProps 是经过身份验证的。启动状态为空。如果为空,则重定向登录,否则呈现管理组件
标签: reactjs routes react-router-dom react-apollo aws-amplify