无法使用 useState 处理反应微调器加载

Can't handle react spinner loading using useState

我使用的是功能组件,所以我必须使用 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
 )

}

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

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

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

问题是您正在以同步方式尝试异步操作。你应该等到你的 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 进一步阅读,它有例子和一切。