React(四)之fetch请求数据,fetch异步请求reac

2019-04-22  本文已影响0人  喵呜Yuri

加载之初需要我们从后台获取数据。
没有后台的情况下可以用node.js做模拟服务器:
在项目下/public/test/api中新建data.json文件
建在public里面是因为该文件不参与构建和打包
src里面的文件参与构建

使用nodejs开发的一个服务器serve,初次使用的话应该是没有的,安装一个

$npm install -g serve
cd  XXX/public/test/
$serve

显示:


image.png

打开浏览器访问localhost:5000/api/data.json便能获取

打开另一个cmd启动我们的react项目
在react组件挂载阶段中,像 Ajax 数据的拉取操作、一些定时器的启动等,就可以放在 componentWillMount 里面

安装fetch

$npm install whatwg-fetch --save
npm install es6-promise --save

组件中引用并应用:

import  'whatwg-fetch'
...
componentWillMount (){
fetch(“localhost:5000/api/data.json”)
        .then(response => response.json())
        .then(json => {
             console.log('i get'+json)
        })
        .catch(e =>  {
           console.log('服务器报错'+e)
 })
}
image.png

报错,3000端口访问5000端口属于跨域
在 packager.json中添加“proxy”属性:

 "proxy": {
    "/api": {
      "target": "http://192.168.31.1:5000"
    }
  }

不写localhost://5000是因为这种写法时好时坏
cmd重启项目


image.png

报错原因是配置项中的“react-scripts”版本过高,重装一下1.1.1版本的

$npm install react-scripts@1.1.1

cmd重启项目,好了。接口我们改一下:

fetch(“/api/data.json”)。。。

获取正常。

网上说react-thunk的引用场景是fetch加载数据,loading加载等。。不用react-thunk也能做到啊。。
那对我来说,react-thunk的作用是:
dispatch一个函数
一般来说dispatch接受一个对象作为参数,reducer通过switch对象的type命来启动操作
但当我们需要触发多dispatch逻辑应用时,一般我都当作请求数据时的公共方法在用:

import {toggleloading,togglemsg} from '../redux/action/layer'
export const fetchPosts = (postTitle,Fn) => (dispatch, getState) => {
    dispatch(toggleloading(true));//加载loading
    return fetch(postTitle)
        .then(response => response.json())
        .then(json => {
            setTimeout(()=>{
                dispatch(toggleloading(false));//关闭loading
                return Fn(json);//回调函数处理结果
            },1000)
        })
        .catch(e =>  {
            dispatch(toggleloading(false));
            dispatch(msgFn('服务器报错'))
        })
}

这个dispatch中传入了一个函数哦,那如何让dispatch接受一个函数作为参数呢?
react-thunk派上了用场:

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

let store = createStore(
    rootReducer,
    applyMiddleware(thunk)
);

export default store;

你的store需要加点applyMiddleware(thunk),此时thunk作为中间件,这个applyMiddleware作为中间件数组,还可以放其他,注意日志中间件要放在最后。
在组件中如何应用呢?

import {fetchPosts} from '../../lib/common'
。。。
 componentWillMount(){
        // this.props.toggle_msg('iam comi!!!');
        this.props.fetchPosts('/api/data.json',(res)=>{
            this.props.getgoodlist(res.data.songs);
        })
    }

前提是在mapDispatchToProps中声明该方法:

const mapDispatchToProps = (dispatch) =>({
    fetchPosts:(url,fn)=>dispatch(fetchPosts(url,fn))
})
上一篇 下一篇

猜你喜欢

热点阅读