问题描述
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>
);
};
我想在等待承诺解决的同时添加一个微调框。 fetchMusic在其他文件中。我将其导入组件中。
解决方法
TLDR
将
useState
和useCallback
用于该操作怎么样
答案
在反应方面,使用State
进行加载操作是正确的用例。
因此,在启动功能时,可以使用setLoading(true)
罐,之后可以setLoading(false)
使用make加载效果
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>
);
};
参考
ETC
如果还有其他问题。请给我评论。