前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >redux学习记录

redux学习记录

作者头像
biaoblog.cn 个人博客
发布2022-08-11 18:58:34
1560
发布2022-08-11 18:58:34
举报

redux中的state:

1.安装redux

代码语言:javascript
复制
$ npm i redux --save

2.进行引入:

代码语言:javascript
复制
import { createStore } from 'redux'

3.创建reducer进行管理

代码语言:javascript
复制
const defaultState = {
 list:[
 '早8点开晨会,分配今天的开发工作',
 '早9点和项目经理作开发需求讨论会',
 '晚5:30对今日代码进行review'
 ]
}
export default (state=defaultState,action)=>{
 return state
}

4.在仓库中进行引入:

代码语言:javascript
复制
import reducer from './reducer'

5.创建数据管理仓库并注入reducer并把仓库暴露出去:

代码语言:javascript
复制
const store = createStore(reducer)
export default store;

6.在组件中进行引入:

代码语言:javascript
复制
import store from './store'

7.获取到仓库中的数据

代码语言:javascript
复制
console.log(store.getState())

reducer中的action:

1.在组件中写个方法并创建action

代码语言:javascript
复制
test(){
 const action = {
	type:"getItem"
}

//把action派遣到仓库中

代码语言:javascript
复制
store.dispatch(action)

2.在reducer中根据action的type进行操作:

代码语言:javascript
复制
export default(state=defaultState ,action){
 // 在reducer中只能接收state但不能改变 (只读),所以用newState 进行拷贝。
	let newState = state
 if(action.type === "getItem'' ){
 //模拟添加一条
 newState.list.push(newState.inputVal)
 //返回 newState其实就是实现仓库数据的更新
 return newState
}
}

3.在react老版本中,仓库进行了更新了以后,需要在组件中进行订阅(subscribe)。

代码语言:javascript
复制
class TodoList extends Component {
 constructor(){
 super()
 this.state = store.getState()
 this.storeChange = this.storeChange.bind(this)
 //订阅Redux的状态 改变仓库的状态
 store.subscribe(this.storeChange)
 }

4.在组件里面写一个方法storeChange,其实就是又去获取一下store的状态。

代码语言:javascript
复制
 storeChange(){
 // 需要使用this.setState()
 // getState是store的固定函数 获取状态
 this.setState(store.getState())
 }

5.actionType的优化方法:创建一个actionType的文件。

代码语言:javascript
复制
export const GET_ITEM = 'getItem'

6.在组件和仓库中进行引入和调用。

代码语言:javascript
复制
import {GET_ITEM } from './store/actionType'

优势:快速显示报错。

7.action方法的优化,建立单独的js文件,进行创建、并在组件中引用使用:

代码语言:javascript
复制
import {CHANGE_INPUT,ADD_VALUE,DEAL_ITEM} from './actionType'
 const changeInputAction = (value)=>({
 type:CHANGE_INPUT,
 value:value
 })
const addValue = () =>({
 type:ADD_VALUE,
})
const dealItem = (index) =>({
 type:DEAL_ITEM,
 index:index
})
export {
 changeInputAction,
 addValue,
 dealItem
}

组件中通过:const action = changeInputAction(value) 并 dispatch(action)

reducer需要注意的三点:

1.Store必须是唯一的

2.只有store能改变自己的内容,Reducer不能改变(通过return newState)

3.Reducer必须是纯函数。纯函数:如果函数的调用参数相同,则永远返回相同的结果。它不依赖于程序执行期间函数外部任何状态或数据的变化,必须只依赖于其输入参数。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • redux中的state:
  • reducer中的action:
  • reducer需要注意的三点:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档