react(跨域、axios、fetch、React全局数据控制(redux))框架

Axios请求与redux全局

跨域

定义:

token原理:

同源策略

react脚手架的两种跨域

跨域问题

方式一

通过package.json跨域

方法二

方法一已经实现了跨域,但是,不够灵活,只能全局设置一个跨域地址。

可以借助三方的插件http-proxy-middleware灵活跨域

npm i http-proxy-middleware -D
npm install --save-dev http-proxy-middleware

配置跨域的文件需要在src目录下创建setupProxy.js文件,写法固定

const createProxyMiddleware  = require('http-proxy-middleware');
​
module.exports = function(app){
        app.use(createProxyMiddleware('/api',{
            target: 'http://127.0.0.1:3001' 
        })       
    )
}

axios

安装

npm i axios -S

axios({
    url: "url",
    method: "post",
    headers: {},
    data: {}
}).then(res=>{
​
}).catch(error=>{
​
})

get

axios.get('http://localhost:3001/api/getgoods',{headers:{},params:{}}).then(res=>{
    console.log(res)
}).catch(error=>{
    console.log(error)
})

POST

axios.post('http://localhost:3001/api/getgoods',headers:{},data:{}).then(res=>{
    console.log(res)
}).catch(error=>{
    console.log(error)
})
axios.post(url).then(res=>{})

封装

import axios from "axios";
import {Component} from "react";
​
// axios.defaults.baseURL = "/api"
​
axios.interceptors.response.use(response=>{
    return response.data
})
​
Component.prototype.$http = axios
​
export default axios

 

fetch

类似axios

fetch是高级浏览器内置的一个发送数据请求的API >IE8.0

fetch底层基于Promise

fetch依然会受到同源策略的限制

GET

var url = '/api/getgoods'
fetch(url).then(
    res=>{
        return res.json()//当前步骤只是接受到了响应对象,不能在这里看到响应数据
    }
).then(
    res=>{
        console.log(res,"++++++++++++++++++++++++++++")
    }
)
​

fetch默认式get请求,所以请求头设置部分可以省略,完整写法如下

var url = '/api/getgoods'
fetch(url,{
    method: "GET",
    headers: {}
}).then(
    res=>{
        return res.json()//当前步骤只是接受到了响应对象,不能在这里看到响应数据
    }
).then(
    res=>{
        console.log(res,"++++++++++++++++++++++++++++")
    }
)

POST

var url = '/api/getgoods'
fetch(url,{
    method: "POST",
    headers: {
        'Content-Type': "application/json"
    },
    body: JSON.stringify({
        username: "root",
        password: "123"
    }),
}).then(
    res=>{
        return res.json()//当前步骤只是接受到了响应对象,不能在这里看到响应数据
    }
).then(
    res=>{
        console.log(res,"++++++++++++++++++++++++++++")
    }
)

封装

封装代码

export function request(url,method="GET",body={},headers={}){
    const option = {
        method,
        headers: Object.assign({"Content-Type": "application/json"},headers)//合并对象,设置默认头
    }
    if(method === "POST"){
        option.body = JSON.stringify(body)
    }
    return fetch(url,option).then(response=>{
        return response.json()
    })
}

使用

React全局数据控制(redux)

redux是一个react的状态管理工具, 作用就是帮助我们管理一些需要在组件之间进行共享的数据

下载

npm i redux -S

基本结构

import {createStore} from 'redux'
​
const init_list = [
    {
        id:3,
        name: "张三",
        age: 18
    },
    {
        id:2,
        name: "李四",
        age: 18
    },
    {
        id:1,
        name: "王五",
        age: 18
    }
]
​
function personList(state = init_list,action){
    switch (action.type){
        case 'insert':
            console.log("这里是插入")
            break
        case 'delete':
            console.log("这里是删除")
            break
        case 'update':
            console.log("这里是修改")
            break
        case 'select':
            console.log("这里是条件查询")   
            break 
        default:
            return state
    }
    
}
​
const store = createStore(personList) //创建一个store对象
​
export default store

store对象

常用方法

getState 获取store当中的数据
dispatch 传入剧本,调用store封装的函数的指定部分

基本操作

完成案例

列表数据的增删改查

定义格式

npm i antd -S

import React, { Component } from 'react'
import store from '../redux'
import { Table, Input } from 'antd';
import '../asserts/css/layout.css'
export default class Layout extends Component {
    state = {
        dataSource: [],
        columns: [
            {
                title: '编号', //表头字段
                dataIndex: 'id', //调用数据对应的字段 table.id
            },
            {
                title: '姓名',
                dataIndex: 'name',
​
            },
            {
                title: '年龄',
                dataIndex: 'age',
​
            },
        ]
    }
    UNSAFE_componentWillMount() {
        this.setState({
            dataSource: store.getState()
        });
    }
    render() {
        return (
            <>
                <div class="yangshi">
                    <Input placeholder="Basic usage" />
                    <Table dataSource={this.state.dataSource} columns={this.state.columns} />
                </div>
            </>
        )
    }
}
​

1、 不能多次返回同一个对象,在reduser当中,不可以返回原生的state

2、store.getState()获取的reduser返回的数据,但是当指向dispatch之后,获取的是dispatch修改的数据

代码如下:

reducer代码

redux/index.js

import {createStore} from 'redux'
​
const init_list = [
    {
        id:3,
        name: "张三",
        age: 18
    },
    {
        id:2,
        name: "李四",
        age: 18
    },
    {
        id:1,
        name: "王五",
        age: 18
    }
]
​
function personList(state = init_list,action){
    switch (action.type){
        case 'insert':
            var id = state.length>0?state[0].id+1:1
            let {name,age} = action.data
            var obj = {
                id: id,
                name:name,
                age:age
            }
            return [obj,...state] //不能多次返回同一个对象,在reduser当中,不可以返回原生的state
        case 'delete':
            console.log("这里是删除")
            break
        case 'update':
            console.log("这里是修改")
            break
        default:
            return state
    }
    
}
​
const store = createStore(personList) //创建一个store对象
​
export default store

layout.jsx

import React, { Component } from 'react'
import store from '../redux'
import { Table, Input,Form,Button } from 'antd';
import '../asserts/css/layout.css'
export default class Layout extends Component {
    state = {
        dataSource: [],
        columns: [
            {
                title: '编号', //表头字段
                dataIndex: 'id', //调用数据对应的字段 table.id
            },
            {
                title: '姓名',
                dataIndex: 'name',
​
            },
            {
                title: '年龄',
                dataIndex: 'age',
​
            },
        ]
    }
    UNSAFE_componentWillMount() {
        this.setState({
            dataSource: store.getState()
        });
    }
    submit(value){
        store.dispatch({
            type: 'insert',
            data: value
        })
        this.setState({
            dataSource: store.getState()
        });
    }
    render() {
        return (
            <>
                <div className="yangshi">
                    <Form
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        initialValues={{ remember: true }}
                        autoComplete="off"
                        onFinish={this.submit.bind(this)}
                    >
                        <Form.Item
                            label="用户名"
                            name="name"
                        >
                            <Input />
                        </Form.Item>
​
                        <Form.Item
                            label="年龄"
                            name="age"
                        >
                            <Input />
                        </Form.Item>
​
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                保存
                            </Button>
                        </Form.Item>
                    </Form>
​
                    <Table dataSource={this.state.dataSource} columns={this.state.columns} />
                </div>
            </>
        )
    }
}
​

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值