react开发教程(十)redux结合react
描述Redux 和 React 之间没有关系。Redux 可以搭配 React、Angular 甚至纯 JS。但是 Redux 还是比较适合和 React 搭配的,因为 React 允许你以 state 的形式来描述界面,而 Redux 非常擅长控制 state 的变化。 Redux 和 React 的结合需要用到 redux-react 这个库 案例说明目录├── README.md ├── index.js ├── action │ └── home.js │ └── about.js ├── actionType │ ├── index.js ├── reducer │ └── home.js │ └── about.js │ └── index.js └── view └── Home.jsx └── About.jsx ActionType抛出两个type常量 export const SET_AGE = 'SET_AGE' export const SET_NAME = 'SET_NAME' Action创建动作 //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规则//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({},{ 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 } ) viewbindActionCreators:把 action creators 转成拥有同名 keys 的对象,但使用 dispatch 把每个 action creator 包围起来,这样可以直接调用它们。 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; index.js
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基础 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |