简体   繁体   English

在等待 promise 在反应中解决时添加一个 Spinner

[英]Add a Spinner while waiting for promise to resolve in react

const fetchMusic= () => {
  return new Promise((resolve) =>
    setTimeout(() => {
      const music = musicList.sort(() => 0.5 - Math.random()).slice(0, 4);
      resolve({ data: music});
    }, 300)
  );
};

export default fetchMusic;


const getRandomMusic = () => {
  return fetchMusic().then((result) => result.data);
};

const Button = (props) => {
  return (
    <div>
      <Button {...props} onClick={getRandomMusic.bind(this)} />
      <SomeComponent /> 
      <p>Some text here</p>
    </div>
  );
};

I want add a spinner while waiting for the promise to resolve.我想在等待 promise 解决时添加一个微调器。 fetchMusic is in some other file.I m importing it in a component. fetchMusic 在其他文件中。我将它导入到一个组件中。

TLDR TLDR

How about use useState and useCallback for that action为那个动作使用useStateuseCallback怎么样

Answer回答

At terms of react, use State for loading action is right use case.在反应方面,使用State进行加载操作是正确的用例。
So, When to start function, use can setLoading(true) and after action you can setLoading(false) for make loading effect所以,当启动 function 时,可以使用setLoading(true)并在操作后使用setLoading(false)来制作加载效果


const fetchMusic= () => {
  return new Promise((resolve) =>
    setTimeout(() => {
      const music = musicList.sort(() => 0.5 - Math.random()).slice(0, 4);
      resolve({ data: music});
    }, 300)
  );
};

export default fetchMusic;

const Button = (props) => {
  const [loaidng, setLoading] = useState(false);
  const getRandomMusic = useCallback(() => {
      setLoading(true)
      return fetchMusic().then((result) => {
        setLoading(false);
        result.data
      });
  },[]);
  return (
    <div>
      <Button {...props} onClick={getRandomMusic.bind(this)} />
      {loading && <Sipinner/>}
      <SomeComponent /> 
      <p>Some text here</p>
    </div>
  );
};

Reference参考

  1. Example of loading 加载示例

ETC ETC

If you have any other question.如果您还有其他问题。 Just give me comment please.请给我评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM