本文共 2411 字,大约阅读时间需要 8 分钟。
本人比较喜欢使用npm 各位也可以使用等
store , action , reducer
store就是保存数据的地方 , 你可以把它看成一个容器或者仓库 , 整个应用只能有一个store
为了方便维护 在src下新建一个reducer文件夹=>index.js 写入如下代码
function reducer(){}export default reducer
在index.js中
import reducer from './reducer'import { createStore } from 'redux'// 创建store , 必须指定reducerconst store = createStore(reducer)
action是一个对象. 其中的 type 属性是必须的 , 表示Action的名称 , 其余属性可以自行设置
action描述的是需要做的事情和携带的数据
在src下创建一个actions文件夹=> index.js
// action 就是一个一个的js对象// action 必须有type属性 , 建议type属性的值纯大写// action 还可以有额外的其他属性// action的作用: 描述要做的事情 , 以及需要的数据export const addUser = { type: 'ADD_USER', username: '张三'}export const add = { type: 'ADD',}
action creator
有多少动作 , 就会有多少个action , 比如添加张三用户 , 添加李四用户 ,删除不同的id任务, 这样一个一个提供action会非常麻烦 ,
定义一个函数来生成Action , 这个函数就叫 Action Creator
action creator的作用:用于生成action
// export function addUser(username) {// return {// type: 'ADD_USER',// username// }// }// 可以简写为export const addUser = (username) => ({ type: 'ADD_USER', username})
reducer就是一个函数 , 它接收 Action 和当前 State 作为参数 , 返回一个新的State
整个应用的初始状态, 可以作为state的初始值
function reducer(state = 0, action) { // 处理action return state}export default reducer
dispatch 派发 action
通过 store.dispatch(action) 可以派发任务 , 把action交给reducer处理
各文件的代码
store文件夹=> actions.js
export const add = () => { return { type: 'ADD' }}export const ww = xw => { return { type: 'XW', xw }}
store文件夹=>reducer.js
function reducer(state = 0, action) { // 处理action if (action.type === 'ADD') { return state + 1 } if (action.type === 'XW') { return state = '小吴是帅比' } return state}export default reducer
其实应该新建一个store文件夹=>index.js
import { createStore } from 'redux'import { add, ww } from '../actions'import reducer from '../reducer'const store = createStore(reducer)// 创建store , 必须指定reducerconsole.log('store', store);// 获取状态 store.getState = 0console.log('获取状态', store.getState());// store派发执行任务store.dispatch(add())// 获取状态 store.getState = 1console.log(store.getState());// 带参数的派发任务store.dispatch(ww('小吴是帅比'))console.log(store.getState());export default store
在index.js文件中
import store from './store'store.getState()
转载地址:http://moswn.baihongyu.com/