使用redux-thunk 中间件进行 ajax 请求的发送

博客指出当异步ajax请求逻辑复杂时,应统一管理。介绍了Redux-thunk中间件,可将异步请求或复杂逻辑放于action中处理。说明了安装方法,还提及在创建store时使用该中间件,最后将异步请求抽出到actionCreators.js文件并修改相关代码。

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

之前我们是把异步ajax 请求直接放在了组件 app.js 中了,当逻辑十分复杂时,我们最好是将这些异步请求放在一个地方进行统一的管理。

下面就是我们之前的代码,看看。

import React, { Component } from 'react';
import './mockdata.js';
import axios from 'axios';
import "antd/dist/antd.css";
import { List, Input, Button } from 'antd';
import store from './store/index.js';


class App extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    this.handleStoreChange = this.handleStoreChange.bind(this);
    store.subscribe(this.handleStoreChange);
  }
  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);
    })
  }
  render() {
    return (
      <div style = {{marginTop: '10px',marginLeft: '10px'}}>
        <div style={{width: '300px'}}>
          <Input
            style={{width: '235px',marginRight: '5px'}}
            value={this.state.inputValue}
            placeholder="Basic usage"
            onChange={this.handleInputChange}
           />
          <Button
            onClick = {this.handleButtonClick}
          >
            Add
          </Button>
        </div>
        <List
          style={{width: '300px'}}
          header={<div>Header</div>}
          footer={<div>Footer</div>}
          bordered
          dataSource={this.state.names}
          renderItem={(item, index) => (<List.Item onClick={this.handleItemCLick.bind(this.index)}>{item}</List.Item>)}
        />
      </div>
    );
  }

  handleInputChange(e) {
    const action = {
      type: 'change_input_value',
      value: e.target.value
    }
    store.dispatch(action);
  }

  handleButtonClick() {
    const action = {
      type: 'add_input_value'
    }
    store.dispatch(action);
  }

  handleItemCLick(index) {
    const action = {
      type: 'delete_Item',
      index
    }
    store.dispatch(action);
  }

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

}

export default App;

非常不清晰。我们可以把这些异步请求放到其它地方。Redux-thunk 中间件可以使我们把异步请求或者复杂的逻辑,放到action 中去处理.

这是rudux-thunk 在github 上的地址 https://github.com/reduxjs/redux-thunk

那么,我们先来安装一下 redux-thunk 

yarn add redux-thunk

然后启动项目

好啦,首先,安装官网说的。在创建store的时候要使用这个中间件。还要引入redux-thunk。再在store 中使用这个中间件,如下。

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';

const store = createStore(
    reducer,
    applyMiddleware(thunk)
);

export default store;

然后可以重启服务了。

下面我们把异步请求抽出来,在src 下新建一个文件 actionCreators.js 。然后呢,我们把异步请求代码放进来,如下。

import axios from 'axios';

export const getTodoItem = () => {
    return () => {
        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);
          })
    }
}

然后,我们再在 app.js 中的componentDidMount 生命周期函数 修改为这样.dispacth中的函数会被自动执行。

  componentDidMount() {
    const getData = getTodoItem();
    store.dispatch(getData);
  }

好啦,我们再更改一下actionCreators.js 文件,如下。

import axios from 'axios';

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值