Dva
https://dvajs.com/
安装
npm install dva-cli -g
dva new dva-quickstart
cd dva-quickstart
npm start
路由
import React, { Component } from 'react';
export default class Products extends Component{
render(){
return (
<h2>List of Products</h2>
)
}
}
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import Products from './routes/Products';
import 'antd/dist/antd.css';
function RouterConfig({ history }) {
return (
<Router history={history}>
<Switch>
<Route path="/products" exact component={Products} />
</Switch>
</Router>
);
}
export default RouterConfig;
组件仓库数据通信
export default {
namespace: 'products',
state: {
name: 'Apple',
songName: '爱情错觉'
},
effects: {},
reducers: {
setSongName(state, action) {
return {
...state,
songName: action.payload.value
}
}
}
}
app.model(require('./models/products').default);
import React, { Component } from 'react';
import { connect } from 'dva';
const namespaced = 'products';
const Xcontent = class Xcontent extends Component {
constructor(props) {
super(props);
this.state = {}
}
updateSongName = () => {
const { dispatch } = this.props;
dispatch({
type: `${namespaced}/setSongName`,
payload: {
value: '余情未了'
}
})
}
render() {
const { products } = this.props;
return (
<div>
<p>{products.songName}</p>
<button onClick={this.updateSongName}>点我修改歌名</button>
</div>
)
}
}
function mapPropsState({ products }) {
return { products }
}
export default connect(mapPropsState)(Xcontent);
配合后端egg.js框架
get请求
demand() {
request('http://localhost:7001/dss?username=llt&id=5').then((res) => {
console.log(res);
})
}
router.get('/dss', controller.home.dss);
async dss() {
const { ctx } = this;
const { username, id } = ctx.request.query;
console.log(username, id);
ctx.body = {
key : '6666'
}
}
post请求
request('http://localhost:7001/find', {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify({
username: "llt",
password: "111"
}),
credentials: 'include'
}).then((res) => {
console.log(res);
})
router.post('/finds', controller.home.find);
async find() {
const { ctx } = this;
const { username, password } = ctx.request.body;
console.log(username, password);
ctx.body = {
key: 'llt'
}
}