@auraxy/redux-usage
v1.0.7
Published
整合 redux-saga,规范 redux 写法
Downloads
3
Readme
@auraxy/redux-usage
pkg.module supported
, which means that you can apply tree-shaking in you project
整合 redux-saga,规范 redux 写法
Installation
# npm i -S @auraxy/redux-usage
Global name
ReduxUsage
Interface
See in index.d.ts
Usage
- Create store
import user from 'src/store/models/user'
import { createReduxStore } from '@auraxy/redux-usage'
const store = createReduxStore([user])
Then, use store
with react-redux in React script
import React from 'react'
import App from '@/views/App'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App store={store} />
</Provider>,
document.getElementById('root'),
)
Define model. Example:
/** src/store/models/user.ts */
import { getUserInfo } from '@/api/User'
import { put } from 'redux-saga/effects'
// Action types
export const USER = {
GET_USER_INFO: 'GET_USER_INFO',
GET_USER_INFO_ASYNC: 'GET_USER_INFO_ASYNC',
}
// model structure
export default {
// model namespace
namespace: 'user',
// model initState
state: {
userInfo: null,
},
// reducer, used to change state synchronously
reducers: {
[USER.GET_USER_INFO](state: any, payload: any) {
return {
...state,
userInfo: payload,
}
},
},
// effect, change state asynchronously by redux-saga
effects: {
async *[USER.GET_USER_INFO_ASYNC](payload: any) {
const userInfo = yield await getUserInfo()
yield put({ type: USER.GET_USER_INFO, userInfo })
},
},
}
- Dispatch action to change state via calling reducer or effect
3.1 Use dispatch by hook.
useReduxDispatch
is a modification of the useDispatch hook exported by react-redux
import React from 'react'
import { useReduxDispatch } from '@auraxy/redux-usage'
import { USER } from 'src/store/models/user'
const Comp = () => {
const dispatch = useReduxDispatch()
// Dispatch
dispatch(USER.GET_USER_INFO, {})
return <div />
}
export default Comp
3.2 Use dispatch from connect.
reduxConnect
is a modification of the connect function exported by react-redux
import React from 'react'
import { reduxConnect } from '@auraxy/redux-usage'
import { USER } from 'src/store/models/user'
const Comp = ({ reduxDispatch: dispatch }) => {
// Dispatch
dispatch(USER.GET_USER_INFO, {})
return <div />
}
export default reduxConnect()(Comp)
- Use state
Use state by hook
import React from 'react'
import { useSelector } from 'react-redux'
const Comp = () => {
const state = useSelector(state => state)
return <div>{state}</div>
}
export default Comp
3.2 Use state from connect.
reduxConnect
is a modification of the connect function exported by react-redux
import React from 'react'
import { reduxConnect } from '@auraxy/redux-usage'
const Comp = ({ state }) => {
return <div>{state}</div>
}
export default reduxConnect(state => ({ state }))(Comp)