簡體   English   中英

使用 redux-thunk 中間件獲取數據

[英]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>
  )
}
  1. 在您的 thunk 中,正確調度操作,即調用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))
    })
  }
}
  1. 在您的存儲庫中, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM