0

我使用一个函数组件,所以我必须使用 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) 之后,但我得到了错误值。 在此处输入图像描述

4

2 回答 2

1

问题是您正在以同步方式尝试异步操作。您应该一直持有,直到您的 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()
}, []);

我强烈推荐这篇文章进一步阅读,它有例子和一切。

于 2020-03-25T11:58:25.187 回答
1

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

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

于 2020-03-25T11:50:15.643 回答