如何依次执行两个异步过程以使用React + Redux获得JSON

问题描述 投票:0回答:2

我正在使用React + Redux。假设我在同一屏幕上有A组件和B组件。A和B都通过异步处理从服务器获取JSON。

但是,我需要将在A中获取的数据用作B的参数。

分派后是否可以运行任何事件?或在渲染A之后执行B的方法。

对抽象问题表示抱歉。

javascript reactjs redux
2个回答
0
投票

一个接一个地检查此同步呼叫。您可以根据所需目标进行修改。

这是您可以根据第一个api响应调用第二个api的方法。

function fetchA(url){
  return fetch(url)
  .then(res=>res.json());
}
function fetchB(url, id){
  return fetch(`${url}/users/${id}`)
  .then(res=>res.json())
}

async function myFunc(url){
 let A = await fetchA(`${url}/posts/3`);
 let B = await fetchB(url, A.id);
 console.log(A)
 console.log(B)
}
myFunc('https://jsonplaceholder.typicode.com');

0
投票

我不确定您为什么会这样做。更多信息可能有助于我们给您我们的意见。也许您可以为您想做的事做一个榜样或嘲笑?

我认为这可能是您的解决方案。希望对您有所帮助。

class A extends React.Component {
  doYourApiCall() {
    // here you do your API call normally. Here's an example of how it could happen
    //
    // fetch(`${url}/someData/`)
    //   .then(res => res.json())
    //   .then(data => {
    //     dispatch({ someData: data.someData });
    //   });
    //
    // When call ended, dispatch your data to Redux to access it in B
  }

  componentDidMount() {
    this.doYourApiCall();
  }

  render() {
    return <div>A</div>;
  }
}

class B extends React.Component {
  componentDidUpdate(prevProps, prevState) {
    // someData is dispatched from A api call
    if (
      this.props.someData !== null &&
      this.props.someData !== prevProps.someData
    ) {
      // make the other api call
      //
      // fetch(`${url}/otherData/${this.props.someData}`)
      //   .then(res => res.json())
      //   .then(data => {
      //     dispatch({ otherData: data.otherData });
      //   });
    }
  }

  render() {
    // this props should be taken in the redux state
    // This way, the B content get rendered only when the props otherData is available
    // Meaning that A component is mounted
    if (!this.props.otherData) {
      return <div>Loading...</div>;
    }

    return <div>B</div>;
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <A />
        <B />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

快乐编码。

© www.soinside.com 2019 - 2024. All rights reserved.