【问题标题】:show loading when fetching data react获取数据时显示加载反应
【发布时间】:2021-11-30 05:20:55
【问题描述】:

我有一个 fetch 调用,用户可以在其中上传图片然后发布。 但是,我想在发布图像时使用加载器向用户显示。我的问题是我的加载程序总是显示。始终显示文本 something is loading。我只想在请求待处理时显示文本。可以请我帮忙吗=

  export default function ImageUpload() {
        const [spinner, setSpinner] = useState(false);
    
      function upload(){
        //some data to post the image
        fetch('my/API/Endpoint'), {
          method: 'post',
          body: body,
        })
       .then(function(data){
          setSpinner(true);
         };
        }
   return (
    <>
       <input type="file"/>
    
        <input onClick={upload}/>
        {spinner && (
        <p>something is loading</p>
        )}
    </>
   );   
        
 }

我确实想指出,发布和获取图像背后的逻辑确实有效,我确实得到了状态 200!它只是不起作用的加载消息

【问题讨论】:

  • 你应该在 fetch 之前使用 setSpinner(true),在 fetch 内部,setSpinner(false)

标签: reactjs post upload fetch


【解决方案1】:

您使用的方法将始终将微调器设置为 true..bcuz .then 始终在 fetch promise 解决后执行...

您需要在调用 fetch 之前将微调器设置为 true,并将 .then 中的微调器设为 false .... 您需要这样的东西

const [spinner, setSpinner] = useState(false);    

function upload(){
 setSpinner(true);

 //some async process
 fetch('my/API/Endpoint'), {
 method: 'post',.0
 body: body,
 }).then(function(data){
 setSpinner(false);
 };
}

【讨论】:

    【解决方案2】:

    你反了没有?

    • 1:将spiiner设置为true

    • 2:在 api 之后设置 spinner 为 false

      const [spinner, setSpinner] = useState(false);    
      
      function upload(){
       setSpinner(true);
      
       //some data to post the image
       fetch('my/API/Endpoint'), {
       method: 'post',
       body: body,
       }).then(function(data){
       setSpinner(false);
       };
      }
      

    【讨论】:

      【解决方案3】:

      在获取完成后,您将微调器状态设置为 true。然后它永远不会再次设置为 false。我期望的行为是文本一开始是不可见的,然后一旦完成提取,它总是可见的。

      您将要在上传函数中将微调器状态设置为 true,然后在 promise 解析器(.then)中设置为 false

      function upload(){
              //some data to post the image
              setSpinner(true)
              fetch('my/API/Endpoint'), {
                method: 'post',
                body: body,
              })
             .then(function(data){
                setSpinner(false);
               };
              }
      

      【讨论】:

        猜你喜欢
        • 2017-07-29
        • 2018-05-27
        • 2016-08-10
        • 2022-06-15
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        相关资源
        最近更新 更多