Redux与Antd
redux与antd
一、redux与antd简介
- redux:是一个可以用在react上的全局状态管理工具。
- antd:是蚂蚁金服开发的一套ui框架。
二、使用antd快速搭建页面
(一)安装antd
- 使用命令
npm i antd --save进行安装。
(二)测试安装是否成功
- 新建
list.js文件- 在
list.js中导入相关组件import React,[ Component]from'react'; import { Button }from 'antd'; import 'antd/dist/reset.css';
- 创建
list组件并在render方法中返回一个包含Button的divexport default class list extends Component{ render(){ return( <div> <Button type="primary">utton</Button> </div> ) } }1
2
3
4
5
6
7
8
9
10
11
12
13
14
152. 在`router`中设置`List`组件的跳转路由
- 导入相关路由组件和`List`组件
- `import{ BrowserRouter, Switch,Route } from 'react-router-dom'; import List from'../views/list';`
- 创建`Routers`函数组件并设置`List`组件的路由
- ```jsx
const Routers=()=>{
return(
<BrowserRouter>
<Switch>
<Route path="/1ist" component={List}></Route>
</switch>
</BrowserRouter>
)
}
export default Routers;
- 在
- 在浏览器手动输入
list地址查看效果- 如果安装成功,会看到一个蓝色的按钮(初次加载会稍微慢点)。
(三)案例制作
- 在
assets文件夹中新建css文件夹用于储存不同组件的样式文件- 新建
list.css文件并导入到list.js中- 在
list.js中导入相关组件和样式文件import React,{Component}from 'react'; import{ Button,Input,List}from 'antd";//导入需要使用的antd组件 import 'antd/dist/reset.css';//导入antd组件样式 import'../assets/css/1ist.css'//导入1ist组件的样式
- 在
list组件的constructor中准备需要被渲染的数据constructor(props){ super(props); //准备需要被渲染的数据 this.state={ arr:['zhangsan','1isi','wangwu'] } }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22- 在`render`方法中返回包含`Input`、`Button`和`List`组件的`div`,并设置相关属性和样式
- ```jsx
render(){
return(
<div className='box'>
<div className="top">
<Input placeho1der="请输入内容'></Input>
<Button className='m-1' type="primary">添加
</Button>
</div>
<div className="bottom">
<List
bordered
dataSource={this.state.arr}
renderItem={item=>(
<List.Item>{item}</List.Item>
)}
/>
</div>
</div>
)
}
- 在
- 新建
list.css样式设置.box{ width:600px; margin:100px auto; } .top{ display: flex;; } .m-l{ margin-left:10px; } .bottom{ margin-top:15px; }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
### (四)代码分析
1. 在父组件中修改子组件的样式
- 在学习vue时知道,vue组件可通过`style`标签的`scoped`属性封闭样式,但外部无法修改,需通过`v-deep`实现修改。
- 而在react中,可以直接找到组件中标签的类名来直接修改,也可以添加新的类名来修改。
2. `antd`的`List`组件的使用
- `antd`组件的使用和`elementPlus`基本一模一样,对于已经学会使用`elementPlus`的人来说基本是直接就拿来用。
- 注意:当前使用的`antd`是针对PC端的,如果要适配移动端可以使用`antd mobile`。
### (五)将`Input`组件制作成受控组件
1. 在`list`组件的`constructor`中设置`textval`用于储存`Input`的`value`的值
- ```jsx
constructor(props){
super(props);
this.state ={ arr:['zhangsan','1isi','wangwu'], textval:"'//设置textva1储存Input的value的值
}
}
- 制作获取
Input的value值的方法getInputvalgetInputval(event){ this.setState({ textval :event.target.value }) }1
2
3
4
5
6
7
8
93. 将每次`Input`输入的内容添加到`arr`数组的前面,从而实时渲染新值的列表项
- ```jsx
addItem(){
this.state.arr.unshift(this.state.textval);
this.setState({
arr:this.state.arr,
textval:"'//每次新增之清除之前输入的内容
})
}
三、redux全局状态管理
(一)安装redux
- 使用命令
npm i redux进行安装。
(二)新建store文件夹及相关文件
- 新建
store文件夹,然后新建两个js文件:index.js和reducer.js。 - 先看
reducer.js管理数据的文件reducer文件负责两件事:- 声明默认状态
const defaultState = {msg:"hello"}
- 导出一个修改状态的函数
export default (state = defaultState,action) => { return state }1
2
3
4
5
6
7
83. `index.js`全局状态管理入口文件
- 导入创建`store`实例的方法和要在实例中引入使用的数据,创建`store`实例并导出
- ```jsx
import {createStore} from "redux" //导入创建store实例的方法
import reducer from './reducer' //导入要在实例中引入使用的数据
const store = createStore(reducer); //创建store实例,然后引用
reducer方法
export default store //导出store实例
- 声明默认状态
(三)代码分析
- 两个文件的关系类似于数据与数据管理员的关系,
reducer.js负责储存操作数据,index.js负责管理reducer的数据。
(四)使用全局状态管理调用案例中的数据
- 在
list组件中从导入的store中使用getState方法来调出全局的状态在当前组件中使用import store from '../store' export default class list extends Component { constructor(props){ super(props); this.state = store.getState() } }1
2
3
4
5
62. 注意事项
- 如果直接覆盖掉原组件中的`state`,可能会把组件自己的状态也覆盖掉,所以可以通过展开运算来获取全局状态
- ```jsx
this.state = {
...store.getState()
}
(五)redux-devtools调试工具
- 安装插件
- 在edge浏览器直接在插件扩展的商店里面搜索
redux-devtools安装。
- 在edge浏览器直接在插件扩展的商店里面搜索
- 在
store的index.js中添加代码import {createStore} from "redux" //导入创建store实例的方法 import reducer from './reducer' //导入要在实例中引入使用的数据 const store = createStore(reducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); //创建store实例,然后引用 reducer方法 export default store //导出store实例1
2
3
4
5
6
7
8
9
10
11
12
13
### (六)修改数据的方法
1. `dispatch`派发方法
- 在`getInputVal`方法中使用`dispatch`方法修改数据
- ```jsx
getInputVal(event){
//使用dispatch方法必须要传入一个action对象,所以我们创建一个action对象
let action = {
type:"textVal",
value:event.target.value
}
store.dispatch(action)
}- 代码分析
action对象中,有两个固定的属性分别是type和value。type:表示本次修改的行为。value:表示本次修改的实际值。然后把设置好的action传入dispatch方法的参数中这里的action会传入到reducer.js中导出的函数的action参数中。
- 在
reducer.js中修改导出方法的业务逻辑const defaultState = { arr:['zhangsan','lisi','wangwu'], textVal:'' } export default (state = defaultState,action) => { if(action.type === "textVal"){ state.textVal = action.value } return state }1
2
3
4
5
6
7
8
### (七)`subscribe`订阅方法
- 解决`Input`数据无法双向绑定更新和全局`state`更新但界面未更新的问题。
1. 在`list`组件中创建`viewChange`方法用于获取每次修改全局`state`修改之后的数据
- ```jsx
viewChange(){
this.setState(store.getState())
}
- 从
store中调用subscribe方法,当redux中的全局state发生变化的时候执行viewChange方法,让组件中的state进行实时更新,再通过setState方法实时渲染到界面上。constructor(props){ super(props); this.state = { ...store.getState() } store.subscribe(this.viewChange.bind(this)) }1
2
3
4
5
6
7
8
9
10
### (八)实现全局`state`和页面数据同步更新
1. 修改`addItem`方法
- ```jsx
addItem(){
let action = {
type:"arr"
}
store.dispatch(action)
}- 代码分析:
- 新增数据已在
Input输入过程同步到全局state中的textVal,这里不需要设置value。
- 新增数据已在
- 在
reducer.js中修改导出方法的业务逻辑const defaultState = { arr:['zhangsan','lisi','wangwu'], textVal:'' } export default (state = defaultState,action) => { if(action.type === "textVal"){ state.textVal = action.value }else if(action.type === "arr"){ state.arr.unshift(state.textVal) state.textVal = "" } return state }1
2
3
4
5
6
7
8
### (九)制作删除功能
1. 在`list`的标签结构上添加删除按钮
- ```jsx
<List.Item>
<span>{item3</span>
<Button type="primary"danger>删除</Button>
</List.Item>
- 制作删除方法
delItemdelItem(index){ let action = { type:"de1" value:index } store.dispatch(action) }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15- 代码分析:
- 删除全局状态需使用`dispatch`方法,且传递索引给`reducer`。
3. 绑定`delItem`方法
- ```jsx
<List
bordered
datasource={this.state.arr}
renderItem={(item,index)=>(
<List.Item>
<span>{item}</span>
<Button onclick={this.delrtem.bind(this,index)}
type="primary"danger>除</Button>
</List.Item>
)}
1>- 代码分析:
- 通过
antd组件List的renderItem获取索引并绑定到delItem方法。
- 通过
- 在
reducer.js中修改导出方法const defaultstate ={ arr:['zhangsan','1isi","wangwu"], textval:" } export default (state = defaultstate,action)=>{ if(action.type==="textval"){ }else if(action.type==="arr"){ state.textval = action.value state.arr.unshift(state.textva1) }else if(action.type==="de1"){ state.textval =" state.arr.splice(action.value,1) } return state }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
### (十)reducer函数写法优化
1. 使用`switch`语句优化`if - else if`判断
- ```jsx
const defaultstate={
arr:['zhangsan','1isi','wangwu'],
textval:"'
}
export default(state = defaultstate,action)=>{
switch(action.type){
case"textval":
state.textval =action.value;
break;
case "arr":
state.arr.unshift(state.textval);
newState.textval="
break;
case "de1":
state.arr.splice(action快照
## 为后期维护提供便利
### (一)把`type`值提取成公用部分
1. 在`store`文件夹内新建`actionTypes.js`
- 注意文件名是固定的不能随便取。
- 内容如下:
- ```js
export const TEXT_VAL = "textVal";
export const ARR = "arr";
export const DEL = "del";- 这里
action的type在取名的时候都是大写,是一个约定熟成的规则。
- 在需要调用的地方解构导入对应需要的
type值,并替换原来list和reducer中的使用type。
(二)把action与dispatch部分提取
- 在
store文件夹中新建actionCreators.js,把之前list组件中用于操作全局state的方法体提取出来import store from './' export default (type,value) => { let action = { type, value } store.dispatch(action) }1
2
3
4
5
6
7
8
9
10
11
12
13
14
152. 在`list`中导入调用并传入对应的实参
- ```js
import {TEXT_VAL,ARR,DEL} from '../store/actionTypes'
import actionCreators from '../store/actionCreators';
export default class list extends Component {
getInputVal(event){
actionCreators(TEXT_VAL,event.target.value)
}
addItem(){
actionCreators(ARR)
}
delItem(index){
actionCreators(DEL,index)
}
}
五、React-redux
(一)原生redux实现简单累加过程
- 新建
react项目操作src文件夹下面只保留App.js和index.js,其他全部删掉。- 把
index.js内部引入的已经被删除的文件导入和调用都删除掉,把严格模式的标签也删除掉。 - 把
App.js中的代码全部删除,替换成类式组件代码。
- 安装原生
redux并创建store- 新建
reducer.js- 设置全局状态(全局数据)
const defaultState = { num:20 }1
2
3
4
5
6
7
8
9
10
11- 导出`reducer`函数(操作全局数据的方法)
- ```js
export default (state = defaultState,action) => {
let newState = JSON.parse(JSON.stringify(state));
switch (action.type) {
case value:
break;
default:
break;
}
return newState
- 设置全局状态(全局数据)
- 在
store内新建index.js- 导入相关内容创建
store实例,并让redux开发工具捕获到实时的全局状态import { createstore } from "redux"; import reducer from "./reducer"; const store= createStore(reducer,window.REDUX_DEVTOOLS_EXTENSION_&& window.REDUX_DEVTOOLS_EXTENSION_(O) export default store1
2
3
4
5
6
7
83. 创建`Page1.js`组件实现累加
- 在`Page1`组件中:
- `constructor`导入全局状态到`state`
- ```js
constructor(props){
super(props);
this.state = store.getstate();
}
- 制作修改全局状态的方法
toAddtoAddO{ //根据action的type值来决定reducer函数内部执行哪种操作修改全局状态 let action={ type:"todd" } //将action派发给全局状态 store.dispatch(action) }1
2
3
4
5
6
7
8- `render`方法返回相关元素
- ```js
render(){
return(
<div>
<p>{this.state.num3</p> <button onclick={this.toAdd.bind(this)}>按钮</button>
</div>
}
- 导入相关内容创建
- 在
reducer.js中修改switch判断为toAdd时,将全局状态中的num执行递增运算export default (state = defaultState,action) => { let newState = JSON.parse(JSON.stringify(state)); switch (action.type) { case "toAdd": newState.num++; break; } return newState1
2
3
4
5
6
7
8
9
10
### (二)通过`subscribe`订阅实时变化
1. 在`Page1`组件中
- `constructor`订阅`store`中的`num`变化
- ```js
constructor(props){
super(props);
this.state = store.getState();
store.subscribe(this.viewChange.bind(this))
}
viewChange方法实现双向绑定viewChange(){ this.setState(store.getState()) }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
### (三)react-redux优化
1. 安装包
- 使用命令`npm i react-redux`安装。
2. `Provider`提供器组件
- 在`index.js`入口文件中导入`Provider`作为顶层组件使用
- ```js
import App from './App';
import { Provider } from 'react-redux';
import store from './store';
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
- 代码分析:
Provider作为一个提供器组件,通过其store属性将全局数据提供给其所有的子组件,所以需要把Provider组件写在最外层。
- 新建
connect连接器方法- 在需要使用全局状态的组件中导入
connect方法。 - 第一次执行时传入两个回调函数:
- 参数1:
state的映射函数mapStateToPropsconst mapStateToProps=state=>{ return{ num:state.num } }1
2
3
4
5
6
7
8
9
10
11
12- 参数2:`dispatch`的映射函数`mapDispatchToProps`
- ```js
const mapispatchToProps =dispatch=>{
return{
toAddO){
let action={
type:"toAdd"
}
dispatch(action)
}
}
}
- 参数1:
- 第二次执行时传入一个组件名作为参数,将打包的内容注入到组件中,使组件能使用全局
state的数据。 - 在
Page组件中导入connect方法并进行相关操作:- 创建映射全局状态的函数
mapStateToProps。 - 导入并使用
connect方法import React,{ Component } from 'react' import store from '../store' import{ connect}from 'react-redux'; class Page1 extends Component{ //把原来的constructor和viewChange直接可以删除掉了 toAddO{ let action={ type:"toAdd" } store.dispatch(action) } render(){ return( <div> <!--connect注入的全局数据要从props中调用--> <p>{this.props.num}</p> <button onclick={this.toAdd.bind(this)}>按钮</button> </div> ) } } export default connect (mapStateToProps) (Page1)1
2
3
4
5
6
7
8
9
10
11
12
13
14- 注意事项:
- 把`mapStateToProps`作为`connect`实参传入,`mapStateToProps`中`return`的对象会成为第二次执行时组件内部的`state`使用,但数据要从`props`里面调用。
- 原因是`connect`方法注入的全局数据是通过`Provider`组件提供的,`Provider`作为顶层组件,是父组件向子组件传值的过程,所以数据从`props`中调用。
- 再传入`dispatch`的映射函数`mapDispatchToProps`
- ```js
const mapispatchToProps =dispatch=>{
return{
toAddO){
let action={
type:"toAdd"
}
dispatch(action)
}
}
- 这样所有修改全局
state的方法都会挂到props对象上面,所以在调用toAdd方法的时候需要从props中调用。
- 创建映射全局状态的函数
- 相关组件渲染操作
render(){ return( <div> <p>{this.props.num3</p> <!--toAdd方法要从props中调用--> <button onclick={this.props.toAdd.bind(this)}>按钮 </按钮> </div> ) }
- 在需要使用全局状态的组件中导入
- 补充内容
- 当完成了上述操作之后,组件无需导入
store,因为Provider组件已经将store提供给了通过connect方法返回并导出的组件中了。 - 解释
mapStateToProps和mapDispatchToProps获取参数的原因:Provider将store作为组件属性传入并提供数据。
- 备注:
react-redux只是对组件内操作全局state的写法进行了优化,对原本的redux中的reducer和index文件并没有影响。
- 当完成了上述操作之后,组件无需导入
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 前端学习笔记!