redux学习总结javascript
主要是学习完,为了加深印象,整理的一些概念和总结,主要是参考阮大师的文章。css
<Provider store={store}>
引入。由于provider,是连接react和redux的,全部import { Provider } from 'react-redux';
import {createStore,applyMiddleware} from 'redux'
。createStore函数接受另外一个函数做为参数,返回新生成的 Store 对象。dispactch,支持异步请求。java
import {createStore,applyMiddleware} from 'redux' import thunkMiddleware from 'redux-thunk' const createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(createStore);
上面代码使用redux-thunk中间件,改造store.dispatch,使得后者能够接受函数做为参数。
所以,异步操做的第一种解决方案就是,写出一个返回函数的 Action Creator,而后使用redux-thunk中间件改造store.dispatch。react
建立一个action,简化作法是createActionweb
import { createAction } from 'redux-actions'; import * as types from '../constants/ActionTypes'; const test = createAction(types.TEST);
Store 收到 Action 之后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫作 Reducer。Reducer 是一个函数,它接受 Action 和当前 State 做为参数,返回一个新的 State。redux
import { createStore } from 'redux'; const store = createStore(reducer);
createStore方法还能够接受第二个参数,表示 State 的最初状态。这一般是服务器给出的。数组
let store = createStore(reducer, window.STATE_FROM_SERVER)
上面代码中,window.STATEFROMSERVER就是整个应用的状态初始值。注意,若是提供了这个参数,它会覆盖 Reducer 函数的默认初始值。服务器
function reducer(state, action) { return Object.assign({}, state, { thingToChange }); // 或者 return { ...state, ...newState }; } // State 是一个数组 function reducer(state, action) { return [...state, newItem]; }
import { handleActions } from 'redux-actions';
import * as types from '../constants/ActionTypes'; const initialState = { }; export default handleActions({ [types.SELECT_LUGGAGE] (state,action){ return { ...state } }, [types.SELECTED_LUGGAGE] (state,action){ var index = action.payload; return { ...state } } },initialState);
import { combineReducers } from 'redux';
import { combineReducers } from 'redux'; const chatReducer = combineReducers({ chatLog, statusMessage, userName }) export default todoApp;
上面的代码经过combineReducers方法将三个子 Reducer 合并成一个大的函数。
这种写法有一个前提,就是 State 的属性名必须与子 Reducer 同名app
React-Redux 将全部组件分红两大类:UI 组件(presentational component)和容器组件(container component)。UI 组件负责 UI 的呈现,容器组件负责管理数据和逻辑。
你可能会问,若是一个组件既有 UI 又有业务逻辑,那怎么办?回答是,将它拆分红下面的结构:外面是一个容器组件,里面包了一个UI 组件。前者负责与外部的通讯,将数据传给后者,由后者渲染出视图。
React-Redux 规定,全部的 UI 组件都由用户提供,容器组件则是由 React-Redux 自动生成。也就是说,用户负责视觉层,状态管理则是所有交给它。异步
React-Redux 提供connect方法,用于从 UI 组件生成容器组件。
~~~
import { connect } from 'react-redux'
const VisibleTodoList = connect( mapStateToProps, mapDispatchToProps )(TodoList) ~~~ 上面代码中,connect方法接受两个参数:mapStateToProps和mapDispatchToProps。它们定义了 UI 组件的业务逻辑。前者负责输入逻辑,即将state映射到 UI 组件的参数(props),后者负责输出逻辑,即将用户对 UI 组件的操做映射成 Action。