简体   繁体   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 is an array of objects having name and year. musicList 是一组具有名称和年份的对象。

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

I want to save the data returned from getRandomMusic function and pass it to SomeComponent component.我想保存从 getRandomMusic function 返回的数据并将其传递给 SomeComponent 组件。

You could use useState ( doc )您可以使用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.

相关问题 React:为什么我不能将数据从一个功能组件传递到另一个功能组件? - React: Why can't I pass data from one functional component to another functional component? 如何在 React 中将数组作为结果从一个功能组件传递到另一个功能组件 - How to pass array as result from one functional component to another in React 从另一个 axios promise 调用 axios 并保存返回的数据 - Make axios call from another axios promise and save returned data 如何通过 React Router Link 将值从功能组件传递到另一个功能组件? - How can I pass values from a functional component through a React Router Link to another functional component? 如何将数据从 vanilla JavaScript 传递到 React 功能组件 - How to pass data from vanilla JavaScript to React functional component 如何使用功能组件将数据从一个组件传递到另一个组件,而无需重新渲染或 jsx,例如 function - How to pass data from one component to another in react without re-render or jsx like from a function using functional components 将数据从组件传递到另一个反应 - Pass data from on component to another react React - 如何将返回的数据从导出函数传递给组件? - React - How to pass returned data from an exported function to a component? 在 React 中将功能组件从子组件传递给父组件 - Pass functional component from child to parent in React Reactjs:将功能组件传递给另一个功能组件以 - Reactjs: Pass functional component to another functional component to
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM