温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

react如何请求数据异步

发布时间:2022-12-28 10:04:05 来源:亿速云 阅读:77 作者:iii 栏目:web开发

这篇文章主要讲解了“react如何请求数据异步”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“react如何请求数据异步”吧!

react请求数据异步的方法:1、通过“npm i redux-thunk --save npm i axios --save”命令下载thunk;2、在store.js里面引入thunk插件;3、在需要模块的actionCreator里引入中间件“redux-thunk”即可。

react异步请求数据方法。

关于react异步请求数据有很多种方案。

1、saga (用了er6生成器函数)

2、promise

3、thunk

4、…

为什么要用插件啊?是为了改造这个redux的action动作。如果异步的话,我们发动作,actionCreator只有返回对象,而异步这个插件能让你隔一段时间再发这个动作,是为了改造动作用的。

本文用thunk,它可能不是最好的,但是是我用得比较习惯的。

一、下载

npm i redux-thunk --save
npm i axios --save

二、引用。在store.js里面引入插件,并使用。

import {createStore,applyMiddleware} from 'redux'   //引入applyMiddleware
import reducers from './reducers'  //总的reducer
import thunk from 'redux-thunk'   //引入thunk 
var store = createStore(reducer,applyMiddleware(thunk));  //使用中间件
export default store;

三、发数据

在你需要模块的actionCreator里:

import axios from 'axios'
export default {
    getData(){
        return (dispatch)=>{   // 引入中间件redux-thunk后,就可以延迟发出动作
                axios.get('http://www.xmyxapp.com/api/tab/1?start=0').then((res)=>{
                    console.log(res)
                    dispatch({
                        type:'GETDATA',
                        list:res.data.data.items.list
                    })
                })
        }
    }
}

四、效果测试

在你需要的模块里面的reducer:

var initState  ={
    list:[]
}
export const listReducer = (state = initState, action) => {
    var newState ={...state};
    switch (action.type) {
        case 'GETDATA':
            newState.list = action.list  // 这个action.list就是该模块actionCreator里传过来的值
            return newState;
        default:
            return state
    }
}

在store里面总和的reducers:

import {combineReducers} from 'redux'
import {listReducer} from '../components/list/reducer'
 var reducer = combineReducers({
     list:listReducer
 })
 export default reducer;

在你需要的模块里面的组件:

import React, { Component } from 'react'
import {connect} from 'react-redux'
import actionCreator from './actionCreator';
 class List extends Component {
  componentDidMount(){
      this.props.getData();   // 调用异步方法获取数据
  }
  render() {
      console.log(this.props);
    return (
      <div>
        <ul>
            {
                this.props.list.list.map((item)=>{
                    return item.title?<li key={item.id}>{item.title}</li>:""
                })
            }
        </ul>
      </div>
    )
  }
}
export default connect((state)=>state,actionCreator)(List);

感谢各位的阅读,以上就是“react如何请求数据异步”的内容了,经过本文的学习后,相信大家对react如何请求数据异步这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI