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

创建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 id
		store.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 (
      
this.input = el} onKeyUp={this.input} />
); } } export default Input;

你可能感兴趣的:(redux)