代码仓库地址:webpack+react+redux+es6
上篇文章有个坑,有个axios
的报错,当时是已经配置好的环境,写文档的时候马虎了没删除,安装这个依赖就好了,本文也会介绍如何使用
- 安装axios依赖
npm install axios
此时你就能使用RESTful API去get、put等方式去请求数据了
- 配置
webpack.dev.config.js
的服务器端配置
//浏览器配置
devServer: {
port: 8888,
contentBase: './public',
inline: true,
openPage: '',
//后台数据请求接口配置
proxy: {
"/api": {
target: "http://localhost:3000",
secure: false,
pathRewrite: {
"/api/": ""
}
}
},
overlay: {
warnings: true,
errors: true
}
}
-
配置了请求端口没有数据也是不开心的,那么接下来就使用json-server和faker.js来创建模拟数据
- 安装依赖
npm install json-server npm install faker
- 在
js
文件夹下创建文件夹mock
并在线创建一个db.js
文件
//db.js const faker = require("faker"); faker.locale = "zh_CN"; const education = [{ label: '初中', value: faker.random.uuid() }, { label: '高中', value: faker.random.uuid() }, { label: '大学', value: faker.random.uuid() }, { label: '硕士', value: faker.random.uuid() }, { label: '博士', value: faker.random.uuid() }] module.exports=()=>{ return { education } }
- 修改配置
package.json
的scripts
命令,添加
"mock": "json-server js/mock/db.js"
执行
npm run mock
,浏览器打开http://localhost:3000/education
界面,你可以在界面上看到数据- 接下来请求数据,修改文件
js/components/count/index.js
文件
import React from 'react' import connect from '@con' import axios from 'axios'; class Count extends React.Component { state = { education: [], value: "3" } componentWillMount() { //后台数据请求 axios.get('/education').then(res => { this.setState({ education: res.data }) }) } /** * 选择框选择事件 */ handleChange = e => { this.setState({ value: e.target.value }); }; render() { return <React.Fragment> <h1>{this.props.count}</h1> <button onClick={() => this.props.add()}>点我</button> <br /> <h3> 下面选择框是请求服务器拿到的数据 </h3> <select value={this.state.value} onChange={this.handleChange}> { this.state.education ? this.state.education.map((data, i) => { return <option key={data.value} value={i} >{data.label}</option> }) : '' } </select> </React.Fragment> } } export default connect("count")(Count)
- 这就是请求的一个例子,在界面会发现一个下拉框,里面的数据就是通过请求
http://localhost:3000/education
得到的数据。
此处讲完了请求数据和创建测试数据,接下来将会讲如何创建多界面应用。
安装react-router相关依赖
npm i react-router react-router-dom -S
- 在
js/components
创建一个类似于count的文件夹及其下面的文件内容。创建js/components/route.jsx
//route.jsx
import React from 'react'
import { HashRouter as Router, Switch, Route, Link, Redirect } from 'react-router-dom'
import { Count, Like } from './index.jsx'
const routes = (
<Router>
<div>
<Link to='/like' replace>走你</Link>
<Switch>
<Route exact path='/' component={Count}></Route>
<Route path='/like' component={Like}></Route>
<Redirect to="/" />
</Switch>
</div>
</Router>
)
export default routes
- 修改界面
js/index.jsx
//...
import routes from './components/route.jsx';
//...
render(
<Provider store={store}>
{routes}
</Provider>
,document.getElementById("root")
)
//...
- 修改
reducers.js
和connects.js
,在按需添加中加入新建的文件like -
Attention
:redux中like文件下的目录结构要跟count的一样
结束语
综上三文,除样式外,所有的配置都已涉及到,各文件的函数功能未详细描述,请自查官档,这里不作描述,谢谢大家