Redux 基本步骤小结:

Redux 基本步骤小结:

1.创建reducer.js

直接导出函数,(state=defaultState,action)=>{… return state;}
先初始化dafaultState
函数体内根据action.type对数据执行不同的操作
(用const newState = JSON.parse(JSON.stringify(state));**对state进行深拷贝)

const defaultState={
	inputValue:'',
	list:[]
}

export default (state=defaultState,action)=>{
	if(action.type === "change_input_value"){
		const newState=JSON.parse(JSON.stringify(state));
		newState.inputValue=action.value;
		return newState;
	}
	retunrn state;
}

2.创建store

采用从redux中导入的createStore()方法创建
第一个参数为从reducer中导入的reducer,第二个参数为浏览器调Redux插件语句

import { createStore } from 'redux';
import reducer from './reducer';

const store = createStore(reducer,
	 window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());


export default store;

3.在component中引入数据

import store from ‘xxx’
用this.state=store.getState()得到数据
在构造函数中加入store的订阅( subscribe() ),让每次数据变化都会自动调用render进行渲染

constructor(props) {
        super(props);
        this.state = store.getState();
        store.subscribe(()=>{this.setState(store.getState())});
    }

4.创建actionTypes.js

明晰要采用的action,将其放在这个文件已变量形式进行输出,统一管理,方便进行debug和测试

export const change_input_value="change_input_value";
export const add_item="add_item";
...

5.创建actionCreateors.js

从actionTypes中引入各个action变量
以函数形式导出各个action函数

import { change_input_value , add_item} from './actionTypes.js';

export const inputChangeAction=(value)=>({
	type: change_input_value,
	value:value
});

export const addItemAction=()=>({
	type: add_item
});

6.component完善

接收actionCreareors中的各个action
赋值给action
发送action到store( store.dispatch(action) )

...
inputText(e){
    	const value=e.target.value;
    	const action=inputChangeAction(value);
    	store.dispatch(action);
    }
...

猜你喜欢

转载自blog.csdn.net/weixin_42268503/article/details/84697449
今日推荐