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)