名词
Redux store 用来存储和控制应用的 state 创建 Redux store 的 redux 方法:createStore
- 创建 Redux store
// Define the store here: const store = Redux.createStore( (state = 5) => state; )
- 从 Redux store 获取 state
const currentState = store.getState()
- 定义 Redux Action
const action = { type: 'ADD_TODO', text: 'Build my first Redux app'}
- 定义 Action Creater function 将 action 发送到 Redux store 中更新 state
const actionCreator = () => { return {type: 'ADD_TODO'} }
- store.dispatch() 将 action 返回给 store
const store = Redux.createStore(
(state = {login: false}) => state
);
const loginAction = () => {
return {
type: 'LOGIN'
}
};
// Dispatch the action here:
store.dispatch(loginAction())
- reducers 管理 actions
(previousState, action) => newState
const authReducer = (state = {login: false}, action) => { switch(action.type){ case'LOGIN': return {login: true} case "LOGOUT": return {login: false} default: return state; } }; const store = Redux.createStore(authReducer); const loginUser = () => { return {type: 'LOGIN'} }; const logoutUser = () => { return {type: 'LOGOUT'} };
- 定义 Action Types 为常量,
const LOGIN = 'LOGIN';
const LOGOUT = 'LOGOUT';
const authReducer = (state = defaultState, action) => {
switch (action.type) {
case LOGIN:
return {login: true}
case LOGOUT:
return {login: false}
default:
return state;
};
const loginUser = () => {
return {type: LOGIN}
};
const logoutUser = () => {
return {type: LOGOUT}
};
- store.subscribe() 每一次 action 执行的时候都会触发,属于事件监听
store.subscribe(listner)
store.subscribe(() => {count++});//监听一个函数
- Redux.combineReducers({key: reducer}) 组合多个 reducers
const rootReducer = Redux.combineReducers({
count: counterReducer,
auth: authReducer
})
- 修改 store 中的 state
const ADD_NOTE = 'ADD_NOTE';
const notesReducer = (state = 'Initial State', action) => {
switch(action.type) {
case ADD_NOTE:
return action.text
default:
return state;
}
};
const addNoteText = (note) => {
return {
type: ADD_NOTE,
text: note
}
};
const store = Redux.createStore(notesReducer);
store.dispatch(addNoteText('Hello!'));
- 利用中间件控制异步 actions
const handleAsync = () => { return function(dispatch) { dispatch(requestingData); //fetch前执行 setTimeout(function() { let data = {users: ['Jeff', 'William', 'Alice']} dispatch(receivedData(data)); //fetch到数据后执行 }, 2500); } }; const store = Redux.createStore( asyncDataReducer, Redux.applyMiddleware(ReduxThunk.default) );
- state 是不可修改的,所以需要拷贝新的 state 进行修改
arr.slice(begin); // [begin, end] arr.slice(begin, end); // [begin, end) //选择的数组的一部分浅拷贝到一个新数组对象。且原始数组不会被修改。 arr.concat(array1) //合并两个或多个数组。不更改现有数组,返回一个新数组。
Object.assign(target, ...sources)
//返回目标对象,从一个或多个源对象复制到目标对象
const newObject = Object.assign({}, obj1, obj2);
