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

【附注信息  ----> 关注公众号:CS阿吉,大家一起分享更多的技术文章,聊天技术问题。】

react axios访问本地json文件

解决方法:必须将json文件放到public文件夹下即可访问

 

(一)使用axios:

//这个算是redux进阶的Demo
import React, { Component } from "react";
import store from "../../store";
import {
  getInputChangeValue,
  getAddItemAction,
  getDeleteItemAction,
  initListAction
} from "../../store/actionCreaters";
import ToDoListUI from './ToDoListUI';

class ToDoListUp extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleStoreChange = this.handleStoreChange.bind(this);
    this.handleButtonClick = this.handleButtonClick.bind(this);
    /**
     * 页面上的内容并没有随着store的更新而更新,所以如下操作:
     * store发生改变,则subscribe()绑定的函数会自动执行
     */
    store.subscribe(this.handleStoreChange);
  }

  componentDidMount() {
      this.axios("http://localhost:3000/mock/list.json").then((res)=>{
            const data = res.data;
            const action = initListAction(data);
            store.dispatch(action);
      }).catch(err=>{
          console.log(err);
      })
  }

  // input值改变触发action
  handleInputChange(e) {
    //定义action两种方式,下面是最原始的一种:(1)
    // const action = {
    //   type: CHANGE_INPUT_VALUE,
    //   value: e.target.value
    // };
    //下面是改进的方式:(2)
    const action = getInputChangeValue(e.target.value);
    store.dispatch(action);

    console.log(e.target.value);
  }
  // 重新渲染页面数据
  handleStoreChange() {
    this.setState(store.getState());
  }
  // 提交输入内容
  handleButtonClick() {
    const action = getAddItemAction();

    store.dispatch(action);
  }
  // 点击列表电影名字,会删除电影
  handleItemDelete(index) {
    const action = getDeleteItemAction(index);
    store.dispatch(action);
  }

  render() {
    return (
      <ToDoListUI
        list={this.state.list}
        inputValue={this.state.inputValue}
        handleInputChange={this.handleInputChange}
        handleButtonClick={this.handleButtonClick}
        handleItemDelete={this.handleItemDelete}
      />
    );
  }
}

export default ToDoListUp;

 

 

 

 

核心代码

componentDidMount() {
      this.axios("http://localhost:3000/mock/list.json").then((res)=>{
            const data = res.data;
            const action = initListAction(data);
            store.dispatch(action);
      }).catch(err=>{
          console.log(err);
      })
  }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值