本文內(nèi)容
- 概述Redux原理
- 總結Redux使用
(一)概述Redux原理
個人理解Redux 里面由兩部分組成
store 倉庫用來存放reducer和state
reducer 是用來處理數(shù)據(jù)的。
reducer里面要接受兩個參數(shù)
(1) state 公共數(shù)據(jù)
(2) action用來操作數(shù)據(jù)
action 里面要有兩個參數(shù)
第一個參數(shù)就是 type
第二個參數(shù)就是要修改的值
類型
{
types:"xxxxx",
value
}
(二)Redux使用
(i) action 拆分成兩個文件
(1) types
export const CHANGE_LIST = 'change_list'
export const CHANGE_VALUE = 'change_value'
export const DELETE_ONE = 'delete_one'
(2) action合并
action 實際上就是很多個對象
import * as actionType from './actionType'
export const changelist = () => {
return {
type: actionType.CHANGE_LIST
}
}
export const changeValue = value => {
return {
type: actionType.CHANGE_VALUE,
value
}
}
export const deleteData = index => {
return {
type: actionType.DELETE_ONE,
index
}
}
(ii) Redux里面
之所以引入types是害怕拼寫錯誤
import * as actionType from './actionType'
const defaultState = {
inputValue: '',
list: [
'Racing car sprays burning fuel into crowd.',
'Japanese princess to wed commoner.',
'Australian walks 100km after outback crash.',
'Man charged over missing wedding girl.',
'Los Angeles battles huge wildfires.'
]
}
export default (state = defaultState, action) => {
if (action.type === actionType.CHANGE_VALUE) {
let newDate = JSON.parse(JSON.stringify(state))
newDate.inputValue = action.value
console.log(newDate)
return newDate
}
if (action.type === actionType.CHANGE_LIST) {
let newDate = JSON.parse(JSON.stringify(state))
newDate.list.push(newDate.inputValue)
newDate.inputValue = ''
return newDate
}
if (action.type === actionType.DELETE_ONE) {
let newDate = JSON.parse(JSON.stringify(state))
newDate.list.splice(action.index, 1)
return newDate
}
return state
}
備注
store 必須是唯一的挟鸠,不能出現(xiàn)第二個
只有store才能改變自己的內(nèi)容迹淌,所以reducer里面必須返回一個新的對象瘾带,而不能直接修改state
常用api
createStore() // 創(chuàng)建倉庫
store.dispatch(action) // 發(fā)射子彈
store.getState(); //獲取到公共數(shù)據(jù)
store.subscribe(); // 監(jiān)聽公共數(shù)據(jù)的變化里面?zhèn)鬟f的是一個方法