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 (
      <div className="App">
         <input type="text" ref={(el)=>this.input = el} onKeyUp={this.input} />
      </div>
    );
  }
}

export default Input;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值