【问题标题】:Is there a best practice for managing isLoading state?是否有管理 isLoading 状态的最佳实践?
【发布时间】:2021-08-25 06:50:52
【问题描述】:

对不起,我的英语水平太差了。

假设我想从服务器获取数据并在页面加载时呈现它......逻辑是这样的:

  1. 页面正在加载并显示 Preloader(此时我发送 get 请求)。
  2. 数据被提取并发送到 State。
  3. 预加载器消失,状态数据呈现在页面上。

我的初始状态是这样的:

const state = {
        data: [],
        isLoading: false
      }

我正在做以下事情(代码是关于逻辑的):

  function fetchData() {
    try {
      fetch(URL)
      dispatch({...state, isLoading: true})

          setTimeout(() => {
            dispatch({...state, data: data.payload, isLoading: false})
          }, 500);
        } catch (err) {
          dispatch({...state, isLoading: false})
        }
      }

这是正确的逻辑吗?我不确定这是否是最佳做法....也许我应该这样做:

  function fetchData() {
    try {
      fetch(URL)
      dispatch({...state, isLoading: true})

      setTimeout(() => {
        dispatch({...state, data: data.payload})
      }, 500);
    } catch (err) {
      dispatch({...state, isLoading: false})
    } finnaly {
      dispatch({...state, isLoading: false})
    }

}

那么改变 isLoading 状态的最佳方法是什么?

我正在考虑的第三个选项是创建一个单独的状态 isLoading...我的意思是我必须声明:

  const state = {
    data: [],
  }

  const isLoadingState = {
    isLoading: false,
  }

【问题讨论】:

  • 我不明白为什么会有setTimeout参与。
  • 这是一个基于意见的问题。在第二种方法中,您不需要在 catch 块中将 loading 设置为 false,因为即使出现错误也会调用 finally。
  • @DaveNewton 我认为他正在尝试复制异步操作​​
  • @DaveNewton 没有 setTimeout 预加载器的出现和消失太快了......它有点闪烁

标签: javascript reactjs


【解决方案1】:

你应该在获取之前设置isLoading: true

The finally-block will always execute after the try-block and catch-block(s) have finished executing. It always executes, regardless of whether an exception was thrown or caught.

因此,这取决于您的应用程序的逻辑,但完全可以避免 isLoading: falsetrycatch 块中,并将其设置为 false 只是在 finally 块中。

 async function fetchData() {
    try {
      dispatch({...state, isLoading: true})
      const data = await fetch(URL)  

      dispatch({...state, data: data.payload})
    } catch (err) {
      console.error(err);
    } finnaly {
      dispatch({...state, isLoading: false})
    }

【讨论】:

    【解决方案2】:

    最好在 finally 块中更新加载指示器:

      function fetchData() {
        try {
          dispatch({...state, isLoading: true})
          fetch(URL)
          dispatch({...state})
    
          setTimeout(() => {
            dispatch({...state, data: data.payload})
          }, 500);
        } finnaly {
          dispatch({...state, isLoading: false})
        }
    

    当你的请求完成时它总是会最终阻塞,所以你不需要在你的成功或捕获块中重复设置它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多