如何使用react中axios获取数据

本文介绍了在React应用中如何使用axios库获取数据。首先,需下载axios并引入到项目中。接着,通过dispatch调用actionCreator的getList方法来请求数据。在actionCreators.js中实现getList逻辑,而reducer.js则用于定义初始状态并处理数据更新。最后,在需要展示数据的组件中,通过mapStateToProps将数据连接到state。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

准备工作

  1. 下载axiosnpm install axios --save
  2. 然后在需要调用数据的地方引入import axios from 'axios';

正式开始

  1. 我需要让dispatch派发action给store,告诉store我需要干什么!(这里我通过getList()方法)
const mapDispatchToProps = (dispatch) =>{
    return{
    //handleInputFocus()是我要点击触发的
        handleInputFocus () {
            //getList方法
            dispatch(actionCreators.getList());
        },
    }
}
  1. 然后在actionCreators.js中将getList方法写入
//使用之前一定要下载并且引用
import axios from 'axios';
import {fromJS} from "immutable";

//因为就在同一个文件所以不需要export直接定义就可以了
const changeList = (data) =>{
    return{
        type:actionTypes.GET_LIST,
        //因为传过来的数据是普通的数据所以使用fromJS包裹起来将其变为immutable对象
        data:fromJS(data)
    }
}
export const getList = () => {
    //返回一个对象
    return (dispatch) => {
        axios.get('./api/headerList.json').then((res) => {
            // 获取数据
            const data = res.data
            dispatch(changeList(data.data))
        }).catch((res) => {
            console.log('error')
        })
   }

3.然后在reducer.js中定义默认数据,并且将数据更改

import * as actionTypes from "./actionTypes";
import { fromJS } from "immutable";

const defaultState =fromJS({
    focus: false,
    list:[]
})

export default (state = defaultState,action) => {
    if(action.type === actionTypes.GET_LIST){
        return state.set('list',action.data)
    }
    return state
}
  1. 然后在需要更改的文件夹中的mapStateToProps中定义数据,并且在将其调用。
const mapStateToProps = (state) =>{
    return {
        list: state.header.get('list')
    }
}
//然后在需要调用的地方使用this.props.list.map循环调用
<SearchInfoList>
    {
         this.props.list.map((item) => {
             return <SearchInfoItem key={item}>{item}</SearchInfoItem>
         })
    }
</SearchInfoList>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值