Redux 和 React 之間沒有關係。Redux 能夠搭配 React、Angular 甚至純 JS。可是 Redux 仍是比較適合和 React 搭配的,由於 React 容許你以 state 的形式來描述界面,而 Redux 很是擅長控制 state 的變化。react
Redux 和 React 的結合須要用到 redux-react 這個庫redux
├── README.md ├── index.js ├── action │ └── home.js │ └── about.js ├── actionType │ ├── index.js ├── reducer │ └── home.js │ └── about.js │ └── index.js └── view └── Home.jsx └── About.jsx
拋出兩個type常量segmentfault
export const SET_AGE = 'SET_AGE' export const SET_NAME = 'SET_NAME'
建立動做react-router
//home.js import {SET_NAME, SET_AGE} from '../actionType' export function set_age (age) { return { type: SET_AGE, age } } export function set_name (name) { return { type: SET_AGE, name } } //about.js同上,就是一個模擬,能夠寫不一樣的數據
//reducer/home.js import {SET_NAME, SET_AGE} from '../ActionType' const initialState = { name: '劉宇', age: 100 } export default (state = initialState, action) => { switch (action.type) { case SET_NAME: return Object.assign({}, state, { name: action.name }) case SET_AGE: return Object.assign({}, state, { age: action.age }) default: return state } } //reducer/about.js 同上寫法可自定義 //reducer/index.js import {combineReducers} from 'redux' import home from './home' import about from './about' export default combineReducers( { home, about } )
bindActionCreators:把 action creators 轉成擁有同名 keys 的對象,但使用 dispatch 把每一個 action creator 包圍起來,這樣能夠直接調用它們。
connect:鏈接 React 組件與 Redux store。dom
import React, { Component } from 'react'; import * as pageActions from '../../action' import {bindActionCreators} from 'redux' import {connect} from 'react-redux' class Inbox extends Component { constructor (props) { super(props) console.log(this.props) } render() { return ( <div className="Inbox"> index </div> ) } } function mapStateToProps(state) { return { pageState: state.home } } function mapDispatchToProps(dispatch) { return { pageActions: bindActionCreators(pageActions, dispatch) } } export default connect( mapStateToProps, mapDispatchToProps )(Inbox) // export default Inbox;
將react和redux結合ide
createStore:建立一個 Redux store 來以存放應用中全部的 state。應用中應有且僅有一個 store。
<Provider /> :是由 React Redux 提供的高階組件,用來讓你將 Redux 綁定到 React,讓全部容器組件均可以訪問 store,而沒必要顯示地傳遞它。只須要在渲染根組件時使用便可。this
import React from 'react'; import ReactDOM from 'react-dom'; import {createStore} from 'redux' import { BrowserRouter as Router, Route, Link, Switch, Redirect } from 'react-router-dom' import {Provider} from 'react-redux' import Home from './view/Inbox' import About from './view/About' import rootReducer from './Reducer' //建立store const store = createStore(rootReducer) const BasicExample = () => ( <Router> <div> <Switch> <Route exact path="/home" component={Home}/> <Route path="/about" component={About}/> </Switch> </div> </Router> ) ReactDOM.render( <Provider store={store}> <BasicExample /> </Provider>, document.getElementById('root') );
上一篇:react開發教程(九)redux基礎spa