准备工作
- 下载axios
npm install axios --save
- 然后在需要调用数据的地方引入
import axios from 'axios';
正式开始
- 我需要让dispatch派发action给store,告诉store我需要干什么!(这里我通过getList()方法)
const mapDispatchToProps = (dispatch) =>{
return{
//handleInputFocus()是我要点击触发的
handleInputFocus () {
//getList方法
dispatch(actionCreators.getList());
},
}
}
- 然后在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
}
- 然后在需要更改的文件夹中的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>