您的位置:首页 > Web前端 > React

如何使用react中axios获取数据

2020-04-20 17:16 489 查看

准备工作

  1. 下载axios
    npm 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>
  • 点赞
  • 收藏
  • 分享
  • 文章举报
mini74 发布了37 篇原创文章 · 获赞 1 · 访问量 678 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: