javascript - 使用 redux-thunk 中间件获取数据
问题描述
我正在学习使用 redux-thunk 的 react-redux 异步操作,我想从 API(我的本地数据库)中获取数据,不幸的是,没有获取使用 redux-thunk 中间件数据获取数据,但没有获取 thunk 中间件数据。
所以这里是带有 thunk 中间件的动作创建者,这是行不通的
// retriev comments
export const fetchComments= () =>{
return dispatch =>{
dispatch(fetchCommentsRequest);
axios.get('/api/v1/todo')
.then(response =>{
const comments =response.data;
dispatch(fetchCommentsSucces(comments))
})
.catch(error =>{
const erroMsg =errors.messages
dispatch(fetchCommentsFailure(error))
})
}
}
这是控制台日志结果:
这是一个组件,我在其中调用函数以从 API 获取数据,
import React, {useEffect}from 'react'
import { fetchComments} from '../store/actions'
import { connect } from "react-redux";
function Dashboard(userComments) {
useEffect(() =>{
fetchComments();
}, [])
return (
<div>
<p>Fetching data</p>
</div>
)
}
const mapStateToProps = state => {
console.log("I am state", state);
return {
isAuthenticated: state.Auth.isAuthenticated,
user: state.Auth.user,
userComments: state.comments
};
};
const mapDispatchToProps = dispatch => {
return {
fetchComments: () => dispatch(fetchComments()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
可以在这里找到整个商店:store
有人可以告诉我为什么没有获取数据吗?
解决方案
在组件内部如何fetchComments
调用方法存在问题<Dashboard>
。
一旦 React 组件连接到 Redux 存储,来自存储 ( mapStateToProps
) 的数据以及它可以用来将操作分派到存储 () 的函数将mapDispatchToProps
作为对象传递给该组件。
<Dashboard>
组件接收props
可以在其中访问的对象,如下所示:
function Dashboard(props) {
useEffect(() =>{
props.fetchComments();
}, [])
return (
<div>
<p>Fetching data</p>
</div>
)
}
或使用解构:
function Dashboard({ isAuthenticated, user, userComments, fetchComments }) {
useEffect(() =>{
fetchComments();
}, [])
return (
<div>
<p>Fetching data</p>
</div>
)
}
推荐阅读
- python - Python - 在 Flask 中将查询结果从服务器返回到客户端
- linux - 在 xampp 中发出 manager-linux.run 时出现未知的颜色名称
- c++ - 使视觉工作室项目可移植,问题
- android - 使用我的 Android 应用添加隐私政策的最简单方法
- javascript - 如何使用 localStorage 构建一个简单的 JavaScript 待办事项列表
- php - 如何使用isset发布href链接
- java - Hello World Java 教程 deployNodes 失败
- dart - 创建新的 StatefulWidget 时并不总是调用 createState 方法
- python - 我的性格不会下降。飞扬的小鸟克隆
- r - 用 ggplot 和 par 在 R 中绘制两个图