reactjs - Redux-saga:处理仅在一个组件中使用的异步调用数据的最佳方式
问题描述
我需要有关 redux-saga 和处理异步调用方式的建议。我找不到我的问题的答案。
我想知道如何正确处理异步 API 调用,该调用返回仅在一个组件中使用的数据(因此无法将其存储在商店中)?
在我的 react 应用程序中,我使用 redux-saga 来处理异步调用。当 saga 正确完成时,我会发送一个成功操作,将结果存储在商店中。
但是,当我只想在一个组件中显示结果时,我发现存储结果毫无用处。相反,我想运行一个 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>
);
}
}
希望这可以帮助。
推荐阅读
- c++ - 我想使用 hashmap 打印不重复的数字;
- python - 如何检查 discord.py 中的文件扩展名
- c# - 添加 WCF 服务选项在 VisualStudio 2017 中不可用
- python - Tensorflow 最大递归深度仅在导入时超过
- r - 在 R 中创建一个相关列
- reactjs - 页面上的 2 个反应选择组件 - 一个更改另一个的值
- java - 在 System.out.println 中调用方法时显示错误“Cannot resolve method 'println(void)'”
- generics - expected type parameter `T`, found `&T`
- python - 尝试在 Python 中编写时除外
- python - Python Selenium - 提取表中的所有 URL 并迭代直到下一个按钮消失