简体   繁体   English

在 react-native 功能组件中处理 401 响应

[英]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.

相关问题 Agora React-native 功能组件实现 - Agora React-native functional component implementation React-Native 具有功能组件的 panResponder 阵列 - React-Native panResponder array with functional component react-native 如何将功能组件更改为类组件 - react-native how to change functional component to class component 如何在 react/react-native 中获取功能组件的节点处理程序 - How to get the node handler of a functional component in react/react-native 是否可以从 react-native 中的类组件访问功能上下文? - Is it possible to access functional context from class component in react-native? 如何在反应原生功能组件中应用PropType? - how to apply PropType in react-native functional component? 在 react-native 功能组件中实现初始化代码的位置 - Where to implement initialization code in react-native functional component 如何从 react-native 中的另一个功能组件访问一个功能组件的状态? - How to access one functional component's state from another functional component in react-native? 我们如何在 react-native 功能组件中声明和使用 class 而不用 React.Component 扩展它? - How can we declare and use class in react-native functional component without extending it with React.Component? 在 react-native 中处理付款 - Handling payments in react-native
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM