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)