【问题标题】:How to fetch Data on load component using React-Redux and Axios?如何使用 React-Redux 和 Axios 获取加载组件上的数据?
【发布时间】:2020-07-25 17:49:05
【问题描述】:

我需要在组件加载时从 API 获取数据,我正在使用 axios 获取数据,我需要保存对状态的响应并在组件加载时返回。 但我可以像新手一样做。

我的代码如下。

Sales.js:(这是我获取组件的地方)

function SalesDesk() {
    return (
        <div>
             <FoodScreen />
        </div>
    )}
export default SalesDesk;

FoodScreen.js(这是我需要将结果列出到变量的地方,以便稍后映射)

function FoodScreen() {
    return(
        <div className="sdFoodScreenMain">
        {console.log(items)} // The results should be displayed here
        </div>
    )}
export default FoodScreen;

API.js(这是我使用 axios 路由器的地方)

const API_URL = `https://jsonplaceholder.typicode.com/`; //Mock api for test purposes

export const GetAllItems = () => {
  return (dispatch) => {
      axios.get(API_URL)
          .then(response => {
              dispatch(allItemsList(response.data));
          })
  }
};

ItemsReducer.js(reducer 逻辑)

const ItemsReducer =(state:Array  = null, action) =>{
    if (action.type === 'ALL_ITEMS') {
        return GetAllItems ;
    } else {
        return state= null;
    }
};
export default ItemsReducer

SalesAction.js(操作列表)

export const allItemsList = () => {
    return {
        type: 'ALL_ITEMS'
    };
};

我需要做的就是从 API 获取数据并在组件呈现时将其显示在控制台中。这样我就可以将其显示在 div 框的地图中以备将来使用。对 react 和 Redux 都是新手,所以如果有任何逻辑或实现问题,请忽略。

【问题讨论】:

    标签: reactjs react-redux axios


    【解决方案1】:

    起初 Router.js 是一个坏名字(api.js 等),你应该使用 'react-redux' 中的 { connect } 将 Sales.js 连接到 redux。查看https://redux.js.org/basics/usage-with-react 并调用操作以在 Sales.js 中获取数据

    【讨论】:

      【解决方案2】:

      我必须在组件渲染上添加一个 useDispatch,这样它就可以在加载时将数据提取到组件。

      import Reactfrom 'react'
      import {useDispatch} from "react-redux";
      import {GetAllItems} from 'API' //File containing the axios function
      
      export function SalesDesk() {
      const dispatch = useDispatch();
      dispatch(GetAllItems())
          return (
              <div>
                   <FoodScreen />
              </div>
          )}
      

      这帮助我在组件加载时获取添加到状态。

      【讨论】:

        猜你喜欢
        • 2018-11-14
        • 1970-01-01
        • 2020-09-18
        • 1970-01-01
        • 2020-12-11
        • 2018-07-10
        • 2018-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多