[英]Fetching data with redux-thunk middle ware
我正在使用 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))
})
}
}
这是控制台日志结果:
这是我调用 function 从 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
有人可以告诉我为什么没有获取数据吗?
在<Dashboard>
组件中如何fetchComments
方法存在问题。
一旦 React 组件连接到 Redux 存储区,存储区中的数据 ( mapStateToProps
) 和它可用于将操作分派到存储区 ( mapDispatchToProps
) 的函数将作为 object 传递给该组件。
<Dashboard>
组件接收此props
object 可以在其中访问,如下所示:
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>
)
}
fetchCommentsRequest
function(您提供参考)
export const fetchComments= () =>{
return dispatch =>{
dispatch(fetchCommentsRequest()); //<-----call the fuction
axios.get('/api/v1/todo')
.then(response =>{
const comments =response.data;
dispatch(fetchCommentsSucces(comments))
})
.catch(error =>{
const erroMsg =errors.messages
dispatch(fetchCommentsFailure(error))
})
}
}
fetchCommentsSucces
需要接受一个参数。export function fetchCommentsSucces(comments){ //<----pass argument i.e comments
console.log('success')
return{
type: ActionTypes.FETCH_COMMENTS_SUCCESS,
payload: comments //<----provide correct payload
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.