2025年Taro中使用redux

Taro中使用redux1 在 pages 同级目录新建 3 个文件夹 store actions reducers 应用中所有的 state 都以一个对象树的形式储存在一个单一的 store 中 唯一的改变是触发 action store 创建全局单一的 store actions 用于描述发生什么事件 reducers 用于 action 如何改变 state 树 2

大家好,我是讯享网,很高兴认识大家。

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


store、actions、reducers
应用中所有的state都以一个对象树的形式储存在一个单一的store中。唯一的改变是触发action。
store: 创建全局单一的store。
actions:用于描述发生什么事件。
reducers:用于action如何改变state树。


2、如何获取store里面的state?

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 }) 


讯享网

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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

小讯
上一篇 2025-04-02 14:35
下一篇 2025-02-21 13:51

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/94593.html