[英]Handling 401 responses in a react-native functional component
I'm getting the following warning when an API request returns 401 and I send the user to the login screen:当 API 请求返回 401 并将用户发送到登录屏幕时,我收到以下警告:
Warning: Can't perform a React state update on an unmounted component.
What is the best way to handle this warning in a functional component that uses hooks.在使用钩子的功能组件中处理此警告的最佳方法是什么。 See the code below:
请看下面的代码:
.
.
export default function MovieDetailsScreen() {
const [movie, setMovie] = useState({});
const movieId = useNavigationParam('movieId');
useEffect(() => {
// This is the method that does the request and returns 401 (It
// uses the fetch library)
Client.movies.show(movieId)
.then(result => {
setMovie(result)
})
}, [])
.
.
.
In general, warnings don't crash your application.通常,警告不会使您的应用程序崩溃。 But you should care about them.
但是你应该关心他们。 For instance, the previous warning(s) can lead to performance issues when not properly unmounting your stateful components
例如,当没有正确卸载有状态组件时,之前的警告可能会导致性能问题
the request (eg Promise
) isn't resolved yet, but you unmount the component.请求(例如
Promise
)尚未解决,但您卸载了组件。 Then the request resolves, setMovie()
is called to set the new state, but it hits an unmounted component.然后请求解决,
setMovie()
来设置新的 state,但它遇到了一个未安装的组件。
You can try catch你可以试试抓
Client.movies.show(movieId)
.then(result => {
setMovie(result)
})
.catch((err) => {
Client.movies.stop()
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.