redux 中发送异步请求获取数据

我们实现一下,异步获取远程数据,然后将它显示在todolist 中。

异步数据获取,我们使用axios。

那么我们首先使用一下生命周期函数 componentDidMount ,在周期函数里面发送axios 请求。如下。

import React, {Component} from 'react';
import store from './store/index.js';
import {
  getInputChangeAction,
  getAddItemAction,
  getDeleteItemAction
} from './store/actionCreators';
import TodoListUI from './TodoListUI';
import axios from 'axios';


class BeautifulToDoList extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleStoreChange = this.handleStoreChange.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleItemClick = this.handleItemClick.bind(this);
    store.subscribe(this.handleStoreChange);
  }

  render() {
    return (
      <TodoListUI
        inputValue={this.state.inputValue}
        list={this.state.list}
        handleInputChange={this.handleInputChange}
        handleBtnClick={this.handleBtnClick}
        handleItemClick={this.handleItemClick}
      />
    )
  }

  componentDidMount() {
    axios.get('api/list.json').then((res) => {
      console.log(res);
    })
  }

  handleInputChange(e) {
    const action = getInputChangeAction(e.target.value);
    store.dispatch(action);
  }

  handleStoreChange() {
    this.setState(store.getState());
  }

  handleBtnClick() {
    const action = getAddItemAction();
    store.dispatch(action);
  }

  handleItemClick(index) {
    const action = getDeleteItemAction(index);
    store.dispatch(action);
  }

}

export default BeautifulToDoList;

本来是准备用 Charles ,拦截http 请求,然后映射到本地文件的。但是Charles 怎么着也没有拦截到localhost 的请求,试了好久,应该是我没有配好,放弃。使用mockjs 吧。

mockjs 可以参考 https://github.com/nuysoft/Mock/wiki/Getting-Started

首先我们先下载安装mockjs 到项目中,使用代码 npm install mockjs --save-dev

安装好后,我们在src 下面新建一个文件mockdata.js 文件,然后在这个文件里写下面的内容。

import Mock from 'mockjs';

Mock.mock("api/list.json",{
    "name": "Alice"
})

然后,我们启动服务器就,就在控制台显示数据了。

然后我们在componentDidMount 生命周期函数里,写下面的代码就好。(记得要引入mockdata.js)


import axios from 'axios';
import './mockdata';

  
componentDidMount() {
    axios.get("api/list.json",{dataType: 'json'}).then( res => {
      console.log(res.data);
      const action = {
        type: "init_List",
        value: res.data.names
      };
      store.dispatch(action);
    })
  }

然后,在reducer.js 中添加下面的代码即可。

	if (action.type === 'init_List') {
		const newState = JSON.parse(JSON.stringify(state));
		newState.names = action.value;
		return newState;
	}

好啦,现在项目初始化的 数组就是从远程获取的。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值