Taro中使用redux

1、在pages 同级目录新建3个文件夹。


store、actions、reducers
应用中所有的state都以一个对象树的形式储存在一个单一的store中。唯一的改变是触发action。
store: 创建全局单一的store。
actions:用于描述发生什么事件。
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:标识某个事件
payload: 事件触发时传的数据
(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:为初始值
这个方法是选择city后更新数据。
(4)将state存储到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)

 

 

作者:blossom_6694
链接:https://www.jianshu.com/p/b88e4f1533f5
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值