Taro 使用 redux 筆記

1、在pages 同級(jí)目錄新建3個(gè)文件夾。
store、actions、reducers
應(yīng)用中所有的state都以一個(gè)對(duì)象樹的形式儲(chǔ)存在一個(gè)單一的store中。唯一的改變是觸發(fā)action。
store: 創(chuàng)建全局單一的store。
actions:用于描述發(fā)生什么事件。
reducers:用于action如何改變state樹。
2、如何獲取store里面的state?
(1)定義store

import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import rootReducer from '../reducers'

const middlewares = [
thunkMiddleware
]

if (process.env.NODE_ENV === 'development') {
middlewares.push(require('redux-logger').createLogger())
}

export default function configStore () {
const store = createStore(rootReducer, applyMiddleware(...middlewares))
return store
}

(2)在action 定義里pick city的事件。

export const onCityChange = (city) => {
    return {
        type: PICKER_CITY,
        payload: city
      }
}

type:標(biāo)識(shí)某個(gè)事件
payload: 事件觸發(fā)時(shí)傳的數(shù)據(jù)
(3)在reducer處理pick city事件

const INITIAL_CITY = {
        id: 1,
        name:'北京'
 }

  export default function onCityPick(state = INITIAL_CITY, action) {
    switch (action.type) {
        case PICKER_CITY:
        console.log('action: ' + action)
          return {
            ...state,
            id: action.payload.id,
            name: action.payload.name
          }
         default:
           return state
      }

  }

INITIAL_CITY:為初始值
這個(gè)方法是選擇city后更新數(shù)據(jù)。
(4)將state存儲(chǔ)到store

export default combineReducers({
  pickerCity
})

(5) 獲取store里面的state
定義props

type PageStateProps = {
    pickerCity: {
          id:number,
          name:string
    }
  }

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps;
}

connect 之前定義的state:

@connect(({ pickerCity }) => ({
    pickerCity
}))

取值:

       <View>
            <Text>city id: { this.props.pickerCity.id }</Text>
            <Text>city name: { this.props.pickerCity.name } </Text>
        </View>

2、 如何修改store里面的state?

this.props.onCityChange(city)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容