reducer:初始化state并且接受action动作的处理函数
var me = function(state={name:'',age:''},action){
switch(action.type){
case 'login':
return Object.assign({},state,action.obj)//action.obj对应着action中的obj
}
}
var users = function(state={items:[]},action){
return state
}
var projects = function(state={items:[]},action){
return state
}
action:用户执行的动作函数主要用来改变数据
export function login(obj){
return {
type:'login', //让reducer接受的acrion.type
obj:obj //传递到reducer中的数据
}
}
需要先创建reducer 然后根据再创建action action是view的动作 view是上面绑定的事件就是action的动作。这中间需要一些中间件连接
1.combineReducers
import {combineReducers} from 'redux' 用来将多个reducer连接起来组成一个reducer
F: var reducer = combineReducer({
me,
user,
projects
})
export default reducer //将reducer 导出
1.connect
import {Provider,connect} from 'react-redux' //从react-redux中导入connect 中间件
var Rout = connect(store2props,action2props)(R)
connect 中需要传递两个参数函数 两个参数书序不能乱 后面还需要绑定一个组件 表示传给这个组件(R)的props
1. store2props:
var store2props = function(store){
return {
} //返回一个对象将srore转换为组件的props传给组件
}
2.action2props
var action2props = function(dispatch){
return {
dispatch:dispatch,
//init:()=>dispatch(init()),
//login:(query)=>dispatch(login(query))
init:init,
login:login
}
}//action中的方法传给props 注释部分是另一种写法不用再组件调用时再dispatch```
import React from 'react'
import {
Router,
Route,
IndexRoute,
Link,
hashHistory,
browserHistory
} from 'react-router';
import User from './components/user'
import Login from './components/login'
import Project from './components/project'
import Me from './components/me'
import Page404 from './components/page-404'
import Home from './components/home'
import Repo from './components/repo'
import {Provider,connect} from 'react-redux'
import {init,login} from './action'
var R = React.createClass({
render() {
return (
<Router history={hashHistory}>
<IndexRoute component={Home}/>
<Route path="login" component={Login}>
<Route path="users/:id" component={User}>
<Route path="me" component={Me}>
<Route path="repo/:id" component={Repo}>
<Route path="project" component={Project}>
<Route path="home" component={Home}>
<Route path="*" component={Page404}>
)
},
componentDidMount(){
const {init,login,dispatch} = this.props;
//dispatch(login({name:'lielie2',password:'lielie2'}));
dispatch(init());
}
})
var store2props = function(){
return {}
}
var action2props = function(dispatch){
return {
dispatch:dispatch,
//init:()=>dispatch(init()),
//login:(query)=>dispatch(login(query))
init:init,
login:login
}
}
var Rout = connect(store2props,action2props)(R)
export default Rout
store 需要中间件 createStore
import {createStore, compose, applyMiddleware} from 'redux'
var store = createStore(reducer, compose(applyMiddleware(thunk), window.devToolsExtension()))
//createStore需要将reducer当做参数传入 后面的两项是工具
然后将store 导入主入口组件
例子:
ReactDOM.render(
<div className="App">
<Provider store={store}>//当做props传入
<R/>
document.getElementById('root'))