当前位置: 代码迷 >> 综合 >> redux(一)初步读懂配置redux流程
  详细解决方案

redux(一)初步读懂配置redux流程

热度:92   发布时间:2023-12-14 10:06:17.0

创建state.js:

let state ={todos:JSON.parse(localStorage.todos?localStorage.todos:'[]'),count:localStorage.count?Number(localStorage.count):0
}export default state;

定义action类型名常量count.js:

export const ADD_ACTION ='ADD_ACTION'
export const REMOVE_ACTION = 'REMOVE_ACTION'
export const CHANGE_ACTION ='CHANGE_ACTION'

定义action对象actionCreator.js:

import {ADD_ACTION,REMOVE_ACTION,CHANGE_ACTION}  from "./const"
let createAction = {addAction(title){return {  //action是一个对象  必须有type字段type:ADD_ACTION,title}},removeAction(id){return {  //action是一个对象  必须有type字段type:REMOVE_ACTION,id}},changeAction(id){return {type:CHANGE_ACTION,id}}
}export default createAction;

定义执行对应的action的reducer.js:

import {ADD_ACTION,REMOVE_ACTION,CHANGE_ACTION}  from "./const"import _state from "./state"let reducer = (state=_state,action)=>{let new_state = Object.assign({},state);switch(action.type){case ADD_ACTION:new_state.count++;new_state.todos.push({id:new_state.count,title:action.title,finished:false})break;default:break;}localStorage.todos = JSON.stringify(new_state.todos);localStorage.count = new_state.count;return new_state;
}export default reducer;

安装redux,创建一个仓库实例,传入reducer,store.js:

import {createStore } from 'redux'
import reducer from "./reducer";
let store = createStore(reducer);
export default store;

定义派发action的文件(引入store.js和actionCreator.js),actions.js:

import store from "./store";
import actionCreator from "./actionCreator"let actions = {addAction(title){let act = actionCreator.addAction(title);  //{ type,title}store.dispatch(act);},removeAction(id){let act = actionCreator.removeAction(id);  //{ type,id}store.dispatch(act);},changeAction(id){let act = actionCreator.changeAction(id); //type idstore.dispatch(act);}}export default actions;

组件内绑定事件执行添加的action:

import React, { Component } from 'react';
import actions from "../store/actions";class Input extends Component {constructor(props){super(props);this.input= this.input.bind(this);}input(e){if(e.keyCode==13){//view发出ACTION,改变状态actions.addAction(this.input.value);}}render() {return (<div className="App"><input type="text" ref={(el)=>this.input = el} onKeyUp={this.input} /></div>);}
}export default Input;