首页 > 解决方案 > 使用 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

有人可以告诉我为什么没有获取数据吗?

标签: javascriptreactjsreduxredux-thunk

解决方案


在组件内部如何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>
  )
}

推荐阅读