React笔记(八)
前言
eg:代表代码对照 若文章有误,欢迎读者留言反馈Redux学习【store】
配置store
1 | /* |
ReduxDemo.jsx代码: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
27import React, { Component } from 'react'
// 学习的案例,项目中把store放在入口文件中
import store from '../store/index'
export default class ReduxDemo extends Component {
constructor(props) {
super(props)
this.state = store.getState() // 获取redux中的state
// 加一个监听redux state改变的函数
store.subscribe(() => {
this.setState(() => store.getState()) // 当redux中state改变的时候,自动更新当前的state
})
}
handleClick = () => {
// 同步的actions对象,type是规则,type的值要和reducer中的actions.type对应即可
const userActions = { type: 'increhander', incre: 1 }
store.dispatch(userActions) //store.dispatch(actions对象) 调用reducer中的代码逻辑
}
render() {
return (
<div>
<h3>redux使用</h3>
<p>{this.state.num}</p>
<button onClick={this.handleClick}>+1</button>
</div>
)
}
}
store已经挂载在全局了,然后我们页面中现在如何使用?
1 | import React, { Component } from 'react' |
redux简化版本
规则放到一个文件中
actionTypes.js代码:1
export const increType = 'home/increhander' //常量 字符串随便
导出刚才不同actions,不同写法:
actions.js代码:
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
// 导出刚才不同actions 加3操作
// export const myActions = {
// type:'increhander',
// incre:3
// }
import { increType } from './actionTypes'
// actions写法2 函数形式
export const myActions = (val) => {
return {
type:increType, //'increhander',
incre: val
}
}
// redux使用异步的action,需要安装一个包 redux-thunk 中间件
// npm i -S redux-thunk
// 异步actions 2s后执行加5操作
export const myActionsAsync = (val) => {
return (dispatch)=>{
//写异步逻辑,异步actions需要调用通过action才可以进行操作
setTimeout(() => {
dispatch(myActions(5))
}, 2000);
}
}使用
1 | import React, { Component } from 'react' |