Dva 脚手架 & get请求 & post请求

Dva

https://dvajs.com/

安装

npm install dva-cli -g

dva new dva-quickstart
cd dva-quickstart
npm start

路由

//新建route页面, routes/Products.js,内容如下:

import React, { Component } from 'react';
export default class Products extends Component{
    render(){
        return (
            <h2>List of Products</h2>
        )
    }
}

//添加路由信息到路由表,编辑 router.js :
import Products from './routes/Products';
<Route path="/products" exact component={Products} />

组件仓库数据通信

//第一步:定义Model,在models文件中新建model, models/products.js 
export default {
  namespace: 'products',	//namespace 表示在全局 state 上的 key
  state: {
    name: 'Lemon',
    payload: '你是沙雕吗'
  },
  reducers: {				//reducers 等同于 redux 里的 reducer,接收 action,同步更新 state
    'upd_name'(state,{payload}){
        return{
          ...state,
          payload
        }
    }
  },
};


//第二步:在 index.js 里载入他
app.model(require('./models/products').default);



//第三步:组件关联仓库(例如组件Xcontent)
import React, { Component } from 'react';
import { connect } from 'dva';

const Xcontent = class Xcontent extends Component {
    render() {
        return (
            <div>
                <p>{this.props.products.payload}</p>     //获取仓库的值并渲染
                <button onClick={this.props.set_name}>   //点击修改仓库的值
            		点我有惊喜
            	</button>
            </div>
        )
    }
}
export default connect(
    (state) => {
        return state
    },
    (dispatch) => {
        return {
            set_name: () => {
                dispatch({
                    type: 'products/upd_name',
                    payload: '滚一边玩去'
                })
            }
        }
    }
)(Xcontent);

配合后端egg.js框架

get请求

//前端get请求
demand() {
    request('http://localhost:7001/dss?username=llt&id=5').then((res) => {
        console.log(res);
    })
}

//后端响应
//router.js文件配置路由
router.get('/dss', controller.home.dss);

//home.js文件配置路由映射方法
async dss() {
    const { ctx } = this;
    const { username, id } = ctx.request.query;
    console.log(username, id);
    
    //后端返回数据格式最好为对象或数组
    ctx.body = {
        key : '6666'
    }
}

post请求

//前端post请求
request('http://localhost:7001/find', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
    body: JSON.stringify({
        // 参数名:参数
        username: "llt",
        password: "111"
    })

}).then((res) => {
    console.log(res);
})


//后端响应
//router.js文件配置路由
router.post('/finds', controller.home.find);

//home.js文件配置路由映射方法
async find() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;
    console.log(username, password);
    
    //后端返回数据格式必须为对象或数组
    ctx.body = {        
        key: 'llt'
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38660873/article/details/88546309