【问题标题】:Handling 401 responses in a react-native functional component在 react-native 功能组件中处理 401 响应
【发布时间】:2019-09-29 06:07:59
【问题描述】:

当 API 请求返回 401 并将用户发送到登录屏幕时,我收到以下警告:

Warning: Can't perform a React state update on an unmounted component.

在使用钩子的功能组件中处理此警告的最佳方法是什么。请看下面的代码:

.
.
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)
      })
  }, [])
.
.
.

【问题讨论】:

    标签: react-native expo


    【解决方案1】:

    一般来说,警告不会使您的应用程序崩溃。但是你应该关心他们。例如,之前的警告可能会在未正确卸载有状态组件时导致性能问题

    请求(例如Promise)尚未解决,但您卸载了组件。然后请求解析,setMovie() 被调用来设置新状态,但它遇到了一个未安装的组件。

    你可以试试catch

        Client.movies.show(movieId) 
          .then(result => {
            setMovie(result)
          })
        .catch((err) => {
            Client.movies.stop()
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2019-01-07
      • 1970-01-01
      • 2021-01-08
      • 2021-06-14
      • 2020-05-30
      • 1970-01-01
      相关资源
      最近更新 更多