Redux
state 只读对象,不能直接修改
Reducer 对state进行修改
action 描述用户行为,用于沟通组件和redux
流程
首先组件component中事件触发行为action,分发到reducer中,reducer根据传来的action对state进行处理,state在传递到组件中进行数据的修改
使用react-redux
1、安装
yarn add redux --save yarn add react-redux --save
2、src下创建文件夹redux,redux文件夹下创建文件夹action,action文件夹下创建index.js
/**action 下 index.js**/
/**描述事件的类型,可以单写一个文件里**/
export const type={
ACTION_TYPE:'ACTION_TYPE_VALUE'
}
/**具体的action函数**/
export function actionFun (param){
return{
type:type.ACTION_TYPE,
param//用户触发行为传来的参数
}
}
3、redux文件夹下创建文件夹reducer,reducer文件夹下创建index.js
/**引入事件类型**/
import {type} from '../action'
/**初始化state**/
const initialState={
name:'val'
}
/**导出reducer**/
export default (state=initialState,action){
switch(action){
case type.ACTION_TYPE:
return{
...state,
name:action.param
}
break;
default:
break;
}
}
redux下创建store文件夹,store文件夹下创建index.js
/**初始化store**/
import { createStore } from 'redux'
/**引入reducer对store操作**/
import reducer from '../reducer'
/**建立链接reducer**/
export default ()=>createStore(reducer)
根组件被Provider包着
/**src 下的 index.js**/
import { Provider } from 'redux'
import configStore from 'url/redux/store'
const store=configStore();
<Provider store={store}>
根组件
</Provider>
在组件中使用
1、组件作为触发方
/**通过connect建立于redux的链接**/
import { connect } from 'react-redux'
/**引入行为action,当事件触发,把action分发到reducer中**/
import {actionName} from 'url/redux/action'
组件:
class ComponentName extends Component{
handleClick=()=>{
const {dispatch} = this.props;//建立连接后才可以使用
dispatch(actionName(param))
}
}
export dafault connect()(ComponentName)//建立链接
2、组件引用redux中的数据
import { connect } from 'react-redux'
class ComponentName extends Component{
{this.props.name}
}
const mapState=state=>{
return {
name:state.name
}
}
export default connect(mapState)(ComponentName)
浙公网安备 33010602011771号