在每个页面下都需要有自己独立的store
里面分别包含
index.tsx : 根目录文件用于导出store里的操作
import {reducer} from "./reducer";
import * as actionCreator from './actionCreator'
import * as constants from './constants'
export {reducer, actionCreator, constants}
constants.tsx: 定义常量的action类型
actionCreators.tsx: 异步接口请求和类型派发
reducer.tsx:对action类型判断修改state
- 非异步数据操作()
在当前页面定义一个方法,然后用来派发actionCreators.tsx里返回action类型的方法(这个方法需要关联到props上)
- 组件页面
import {actionCreator as LoginActionCreator} from '../../pages/login/store'
const mapDispatchToProps = (dispatch) = ({
onClickLoginOut: () => {
dispatch(LoginActionCreator.onClickLoginOut())
}
})
- actionCreators.tsx
import * as constants from '../store/constants'
export const onClickLoginOut = () => ({
type: constants.LOGINOUT,
value: false
})
- constants.tsx
export const LOGINOUT = 'login/LOGINOUT'
- reducer.tsx
export const reducer: Rducer = (state= defaultState, action) => {
switch (action.type) {
case constants.LOGINOUT:
return state.set!('login', action.value)
default:
return state
}
}
- 异步数据操作
只需在非异步数据的基础上在actionCreators里在多加一个处理异步的方法即可,接口请求成功后再派发当前文件里返回对应类型的方法
- actionCreators.tsx
const checkLogin = () => ({
type: constants.LOGIN,
value: true
})
export const goLogin = (account: string, password: string) => {
return (dispatch: any) => {
axios.get(`/api/login.json?account=${account}&password=${password}`).then((res) => {
const result = res.data.data
if (result) {
dispatch(checkLogin())
}
})
}
}
组件里只需要派发这个异步的方法即可
const mapDispatch = (dispatch: any) => ({
onClickLogin: (account: string, password: string) => {
dispatch(actionCreator.goLogin(account, password))
}
})
网友评论