♦ 安装插件
cnpm i redux-actions -S
♦ actions代码
import { createActions } from 'redux-actions' export default createActions({ 'HOME_DATA_TYPE': options => options })
♦ reducer代码
import { handleActions } from 'redux-actions' const defaultState = { } export default handleActions({ 'HOME_DATA_TYPE': (state, action) => action.payload }, defaultState)
♦ 派发的action需要转换成驼峰的命名形式才可以使用,这里使用一个封装好的公共方法, 我给其命名为str
export default function (sName) { return sName.toLowerCase().replace(/^\_/, '').replace(/\_([a-zA-Z0-9])([a-zA-Z0-9]+)/g, function (a, b, c) { return b.toUpperCase() + c.toLowerCase() }) }
♦ 页面使用
这里使用hook写的
import React, { useEffect } from 'react' import { connect } from 'react-redux' import homeAction from '@/actions/home' import str from '@/utils/str' export default connect(state => { return { } }, { homeAction: homeAction[str('HOME_DATA_TYPE')] })(Home) function Home(props) { useEffect(() => { const { homeAction } = props homeAction('小花') }, []) return ( <div className="pages-home"> <h1>home</h1> </div> ) }