gpt4 book ai didi

javascript - 如何在 React-router 包装器中处理异步请求

转载 作者:行者123 更新时间:2023-11-29 23:10:08 24 4
gpt4 key购买 nike

我想检查用户是否在我的 React 应用程序中经过身份验证。使用 this指导。

我在我的 <Route /> 上写了一个包装器检查的类,如果用户通过身份验证,那么我们呈现组件,如果没有,我们只是将他重定向到登录页面。

const IsAuthenticatedRoute = function ({ component: Component, ...rest }) {
return (
<Route {...rest} render={async (props) => {
return (
await store.isAuthenticatedAsync() === true // here is the point of troubles
? <Component {...props} />
: <Redirect to={{
pathname: '/sign-in',
state: { from: props.location }
}} />
)
}} />)
}

我在我的路由器中使用它是这样的:

ReactDOM.render(
<Provider store={appStore}>
<Router>
<div>
<Switch>
<Route exact path='/' component={App} />
<IsAuthenticatedRoute path='/protected-route' component={Profile} />
</Switch>
</div>
</Router>
</Provider>
,
document.getElementById('root')
)

我想向服务器执行我的异步请求以检查用户是否已通过身份验证。我试过添加 async我的函数关键字 await调用,但会产生错误:Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead. .我几乎尝试使用 promise ,但这也无济于事。当我使用 Promise在我的函数中返回 <Route />.then()运算符(operator),React 告诉我:IsAuthenticatedRoute(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

所以我希望处理我的异步函数,然后在我从服务器收到响应后,授予我的用户访问此页面的权限。是否只有向我的服务器发送同步请求才有可能,或者还有其他方法可以使我的代码保持异步并将用户传递到 protected 页面?

最佳答案

async 函数不能作为组件呈现,因为您要呈现的是 Promise,而不是纯函数。如果纯函数返回组件的实例,则可以呈现纯函数。 Promise 必须先解决,然后才能呈现。

解决方案是在挂载组件时启动异步调用,并使组件有状态,以便在解析调用时进行变异。您需要在等待响应时渲染一些东西。您可以呈现 null,但加载微调器会更合适。这样我们就可以随时呈现某些内容,并且不会在尝试呈现尚未定义的组件时遇到错误。

这是我对组件的外观的快速破解:

class RouteRender extends React.Component {
constructor(props) {
super(props)
this.state = { authorized: null }
}

componentDidMount() {
// setState is called once the asynchronous call is resolved.
store.isAuthenticatedAsync().then(
authorized => this.setState({ authorized})
)
}

render() {
if(this.state.authorized === true) {
const { component: Component, componentProps } = this.props
return <Component {...componentProps} />
} else if(this.state.authorized === false) {
return (<Redirect to={{
pathname: '/sign-in',
state: { from: props.location }
}} />)
}
return <LoadingSpinner />
}
}

const IsAuthenticatedRoute = function ({ component: Component, ...rest }) {
return (
// render is now a function rather than a Promise.
<Route {...rest} render={props => <RouterRender componentProps={props} component={Component} />} />
)
}

关于javascript - 如何在 React-router 包装器中处理异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53959937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com