javascript - 如何在反应中使用带有 API 调用的 redux?
问题描述
我很好奇如何将从 API 调用中找到的数据存储到 redux 存储中,然后访问它。这是我正在使用的代码。我不熟悉 redux,希望更好地了解如何使用它。
const mapStateToProps = state => {
return {
test: state.simpleReducer.test
};
};
const mapDispatchToProps = dispatch => ({
simpleAction: () => dispatch(simpleAction())
});
class App extends Component {
weatherData = {};
componentDidMount = () => {
this.newAction();
};
newAction = async () => {
let weatherResponse;
await axios({
method: "get",
url: "http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric"
}).then(function(response) {
weatherResponse = [...response.data];
});
this.weatherData = weatherResponse;
console.log(this.weatherData);
};
解决方案
数据的来源并不重要——数据通过以该数据作为有效负载的分派操作进入您的存储,而化简器将该有效负载放入存储中。
因此,当您的请求完成时,您需要调度一个操作,并确保它在减速器中得到处理。
使用connect
react-redux 中的函数将您的 mapDispatchToProps 和 mapStateToProps 函数连接到您的组件,以便您可以发出操作并使用生成的更新状态。
推荐阅读
- virtual-machine - PowerCLI Remove-HardDisk 还会删除控制器
- excel - Excel VBA:如何在弹出/警报消息中显示连接的查询负载状态?
- blazor - Blazor - 如何处理没有网络连接
- python - 使用 Python 从 Teradata 快速导出
- reactjs - gatsby.js 动态加载模块、库
- javascript - 在 Alpine.data 对象中连接数组返回代理
- reactjs - 为什么未定义 useState 值?
- command-line - 无法删除终端文件夹中的数千个文件
- javascript - vuejs element ui - 在 el-select 中添加 html
- git - 两个分支的 git 合并覆盖自定义代码和最新的构建代码