【问题标题】:Can't handle react spinner loading using useState无法使用 useState 处理反应微调器加载
【发布时间】:2020-07-05 21:19:00
【问题描述】:

我使用一个函数组件,所以我必须使用 UseState 来处理组件状态。 我试图在使用 axios 加载数据时显示微调器:

import { Spinner } from 'react-bootstrap';

const MandatesPage = props => {

  const [mandates, setMandates] = useState([]);
  const [loading, setLoading] = useState(false); //  to handle spinner hide show

   useEffect(() => {
    setLoading(true);  // here loading is true
    console.log(loading)
    axios
        .get(`${config.api}/mandates`)
        .then(response => response.data["hydra:member"],setLoading(false)) // here loading is false
        .then(data => setMandates(data))
        .catch(error => console.log(error.response));
}, []);

 ...
  if (loading) return
    return (
        <Spinner animation="border" variant="primary" />
    );
}

return (
   .....  // return the other logic of my app
 )

}

我的问题是微调器未显示,我将 console.log(loading) 放在 setLoading(true) 之后,但我得到了错误值。

【问题讨论】:

    标签: reactjs spinner use-state


    【解决方案1】:

    当然loading 仍然是假的,因为设置是异步的并且只会在下一次渲染时为真。

    对于下一次渲染,将返回加载微调器,因为加载将是 true than。 如果 axios 调用需要短于 16 - 32 毫秒,这是 react 中每个渲染的正常帧,则不会显示加载微调器,因为加载已经被设置回 false。

    【讨论】:

    • 那么我什么时候应该再次设置加载 false 以显示微调器?
    • 调用完成后将其设置为 false 是不行的,但是如果您不必等待,则不需要 s spinner,对吧?
    • 好的,谢谢,我会用大量数据尝试一些好的
    【解决方案2】:

    问题是您正在以同步方式尝试异步操作。您应该一直持有,直到您的 API 响应返回,更像这样:

    useEffect(() => {
      async function fetchMyAPI() {
        let url = 'http://something/';
        let config = {};
        const response = await myFetch(url);
        console.log(response);
      }  
    
      fetchMyAPI();
    }, []);
    

    应用于您的示例:

    useEffect(() => {
      setLoading(true);
      async function fetchOnAxios() {
       const response = await axios.get(`${config.api}/mandates`)
        // Down below inside this function
        // you can set the loading based on the response
      }
      fetchOnAxios()
    }, []);
    

    我强烈推荐this article 进一步阅读,它有例子和一切。

    【讨论】:

    • 感谢您的提问,但我不明白您的 2 个代码之间的区别
    • 没有区别,第一个只是一个示例,说明您应该如何处理在 useEffect 挂钩中获取数据。第二个是将相同的逻辑应用于您的代码。在设置response 之后,您可以执行您对.then 和.catch 执行的任何逻辑
    • 如果您想对您要解决的问题有一个很好的了解,请阅读我的答案底部的链接文章。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2022-01-20
    • 2017-07-29
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多