本文共 1679 字,大约阅读时间需要 5 分钟。
安装create-react-app npm install -g create-react-app 创建项目 create-react-app reactreduxrouterdemo cd reactreduxrouterdemo 安装第三方模块 npm install --save redux npm install --save react-redux npm install --save react-router 修改index.jsimport React, { Component } from 'react';import ReactDOM from 'react-dom';import { createStore } from 'redux';import { Provider, connect } from 'react-redux';//定义组件class App extends Component{ render() { const {text, onChangeText, onButtonClick} = this.props; return (这个例子大概是最简单的了, 而且每一步注释都非常清楚了。 运行工程npm start 源代码工程 https://github.com/chenhaifeng2016/reactreduxrouter); }}//actionconst changeTextAction = { type:'CHANGE_TEXT'}const buttonClickAction = { type:'BUTTON_CLICK'}//reducerconst initialState = { text: 'Hello'}const reducer = (state = initialState, action) => { switch (action.type) { case 'CHANGE_TEXT': return { text: state.text=='Hello' ? 'world':'Hello' } case 'BUTTON_CLICK': return { text: 'Hello world' } default: return initialState; }}//storelet store = createStore(reducer);//映射Redux state到组件的属性function mapStateToProps(state) { return { text: state.text }}//映射Redux actions到组件的属性function mapDispatchToProps(dispatch){ return{ onButtonClick:()=>dispatch(buttonClickAction), onChangeText:()=>dispatch(changeTextAction) }}//连接组件App = connect(mapStateToProps, mapDispatchToProps)(App)//渲染组件ReactDOM.render({text}
, document.getElementById('root'))