如何使用React-Redux和Axios在负载组件上获取数据?

时间:2020-04-13 07:33:17

标签: reactjs react-redux axios

我需要在组件加载时从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来说都是新手,因此请忽略是否存在逻辑或实现问题。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我只需要在组件渲染器上添加一个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>
    )}

这有助于我在组件加载时获取添加状态。