首页 > 解决方案 > Redux-saga:处理仅在一个组件中使用的异步调用数据的最佳方式

问题描述

我需要有关 redux-saga 和处理异步调用方式的建议。我找不到我的问题的答案。

我想知道如何正确处理异步 API 调用,该调用返回仅在一个组件中使用的数据(因此无法将其存储在商店中)?

在我的 react 应用程序中,我使用 redux-saga 来处理异步调用。当 saga 正确完成时,我会发送一个成功操作,将结果存储在商店中。

但是,当我只想在一个组件中显示结果时,我发现存储结果毫无用处。相反,我想运行一个 saga 并通过回调数据返回到我的组件,而不将其存储在存储中。可能吗 ?我怎样才能做到这一点 ?

谢谢。

标签: reactjsreact-reduxredux-saga

解决方案


这是给您的示例代码,该代码在生命周期中发出 api 请求,componentDidMount并将数据设置为其状态并在呈现之后。

import React, { Component } from "react";
import { render } from "react-dom";
import axios from 'axios';

class App extends Component {
  constructor() {
    super();
    this.state = {
      data: []
    };
  }

  async componentDidMount() {
    try {
      let response = await axios.get('https://jsonplaceholder.typicode.com/users');

      console.log('response.data: ', response.data);

      this.setState({
        data: response.data
      });
    } catch (error) {
      console.log('error: ', error);
    }
  }

  render() {
    return (
      <ul>
        {this.state.data.map(item => <li>{item.name}</li>)}
      </ul>
    );
  }
}

希望这可以帮助。


推荐阅读