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

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