簡體   English   中英

保存從 promise 返回的數據並將其傳遞給反應中的另一個組件

[英]Save and pass data returned from a promise to functional another component 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>
  );
};

musicList 是一組具有名稱和年份的對象。

const musicList = [{ 名稱:'abc',年份:1990
},{名稱:'xyz',年份:1989'}]

我想保存從 getRandomMusic function 返回的數據並將其傳遞給 SomeComponent 組件。

您可以使用useState ( doc )

const Button = props => {
  const [musicList, setMusicList] = React.useState([])

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM