react、react-router、redux 也许是最佳小实践2

前端之家收集整理的这篇文章主要介绍了react、react-router、redux 也许是最佳小实践2前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

上一篇react、react-router、redux 也许是最佳小实践1

加入 redux

React 在组件之间流通数据.更确切的说,这被叫做“单向数据流”——数据沿着一个方向从父组件流到子组件。由于这个特性,对于没有父子关系的两个组件之间的数据交流就变得不是那么显而易见。这里 Redux 就排上用场了。Redux提供了一个解决方案,通过将应用程序所有的状态都存储在一个地方,叫做“store”。然后组件就可以“dispatch”状态的改变给这个store,而不是直接跟另外的组件交流。所有的组件都应该意识到状态的改变可以“subscribe”给store。如下图:

原理讲完,下面开始加入代码
先看看一个小例子。

开始之前,需要先用 Redux.createStore() 创建一个store,然后将所有的reducer作为参数传递进去,让我们看一下这个只传递了一个reducer的小例子:

  1. var userReducer = function(state,action) {
  2. if (state === undefined) {
  3. state = [];
  4. }
  5. if (action.type === 'ADD_USER') {
  6. state.push(action.user);
  7. }
  8. return state;
  9. }
  10.  
  11. var store = Redux.createStore(userReducer);
  12.  
  13. store.dispatch({
  14. type: 'ADD_USER',user: {name: 'xiaoming'}
  15. });

上面的程序干了些什么呢:

  1. 这个store只由一个reducer创建。

  2. 这个reducer 初始化状态的时候使用了一个空数组 。*

  3. 在被分派的这个action里面使用了新的user对象。

  4. 这个reducer将这个新的user对象附加到state上,并将它返回,用来更新store。

*在这个例子里reducer实际上被调用了两次 —— 一次是在创建store的时候,一次是在分派action之后。

当store被创建之后,Redux立即调用了所有的reducer,并且将它们的返回值作为初始状态。第一次调用reducer传递了一个 undefined 给state。经过reducer内部的代码处理之后返回了一个空数组给这个store的state作为开始。

所有的reducer在每次action被分派之后都会被调用。因为reducer返回的状态将会成为新的状态存储在store中,所以 Redux总是希望所有的reducer都要返回一个状态。

在这个例子中,reducer第二次的调用发生在分派之后。记住,一个被分派的action描述了一个改变状态的意图,而且通常携带有数据用来更新状态。这一次,Redux将当前的状态(仍旧是空数组)和action对象一起传递给了reducer。这个action对象,现在有了一个值为1ADD_USERtype属性,让reducer知道怎样改变状态。

正式redux登场

src 下面创建一个 reduxactionsdata(存放一些初始数据)文件夹,然后在 data文件夹下面创建一个db.js,这个文件写上一些初始的数据:

src/data/db.js

  1. const data = [
  2. {
  3. id: 1,title: '明天要去打酱油',content: '系呀系呀我们一起打酱油'
  4. },{
  5. id: 2,title: '周末去书吧读书',content: '书籍是人类进步的阶梯'
  6. },{
  7. id: 3,title: '备份一下数据库',content: '备份服务器的数据库,一般都是分开的,分布式数据库'
  8. },{
  9. id: 4,title: '周五记得把被子洗了',content: '洗杯子被子被子被子'
  10. },{
  11. id: 5,title: '计划五',content: '计划五内容'
  12. }
  13. ]
  14.  
  15. export default data

好了,初始的数据我们有了,下面就是创建 store 了,在redux文件夹下面,创建一个planlist.js文件,这个文件就是操作 store 的动作 action集合处理的数据,这时候我们会去action文件夹下面新建,action-type.jsplan.js,代码如下:

src/action/action-type.js

  1. export const ADD = 'ADD';
  2. export const DELECT = 'DELECT';
  3. export const SHOW = 'SHOW';

src/action/plan.js

  1. import * as types from './action-type.js';
  2. // 添加计划
  3. export function addPlan(item) {
  4. return {
  5. type: types.ADD,item
  6. };
  7. }
  8. // 删除计划
  9. export function deletePlan(id) {
  10. return {
  11. type: types.DELECT,id
  12. };
  13. }
  14. // 显示隐藏弹层
  15. export function show(show) {
  16. return {
  17. type: types.SHOW,show
  18. };
  19. }

action 我们都定义好了现在我们就可以改变 store了。写好我们的 reducer

src/redux/planlist.js

  1. import * as types from '../actions/action-type.js';
  2. import data from '../data/db.js'
  3. const initialState = {
  4. show: false,// 是否显示弹出
  5. planlist: data // 初始的计划表
  6. };
  7.  
  8. const planReducer = function(state = initialState,action) {
  9. let list = state.planlist;
  10. switch(action.type) {
  11. // 添加计划
  12. case types.ADD:
  13. list.push(action.item);
  14. return Object.assign({},state,{ planlist: list });
  15. // 删除计划
  16. case types.DELECT:
  17. let newstate = list.filter((item) => item.id != action.id);
  18. return Object.assign({},{ planlist: newstate });;
  19. // 显示、隐藏弹出层
  20. case types.SHOW:
  21. return Object.assign({},{ show: action.show });
  22. }
  23. return state;
  24.  
  25. }
  26.  
  27. export default planReducer;

在redux 下面再创建reducers.jsstore.js

src/redux/reducers.js

  1. import { combineReducers } from 'redux';
  2.  
  3. // Reducers
  4. import planlist from './planlist';
  5.  
  6. // Combine Reducers
  7. var reducers = combineReducers({
  8. planlist: planlist
  9. });
  10.  
  11. export default reducers;

src/redux/store.js

  1. import { createStore } from 'redux';
  2. import reducers from './reducers.js';
  3.  
  4. const store = createStore(reducers);
  5. export default store;

这会我们的 store 就完全的创建好了,下面就是把 store 跟我们的组件,完全的结合起来。这就用到 react-redux 的 connect 模块。
这个东西 就是把组件跟 store 连接起来的模块。

然后在,App.js加入我们的。store

src/App.js

  1. import React,{ Component } from 'react'
  2. import {
  3. BrowserRouter as Router,Route,Link
  4. } from 'react-router-dom'
  5. // 引入 store
  6. import { Provider,connect } from 'react-redux';
  7. import store from './redux/store.js'
  8. import logo from './logo.svg'
  9. import Plan from './components/plan.js'
  10. import Home from './components/home.js'
  11. import Popup from './components/pupop.js'
  12. import TestRouter from './components/testrouter.js'
  13. import Detail from './components/detail.js'
  14. import './App.css'
  15. import './components/comment.css'
  16. import createHistory from 'history/createBrowserHistory'
  17. const history = createHistory()
  18. class App extends Component {
  19. constructor(props) {
  20. super(props);
  21. }
  22. render() {
  23. return (
  24. // store的挂载
  25. <Provider store={store}>
  26. <div className="App">
  27. <div className="App-header">
  28. <img src={logo} className="App-logo" alt="logo" />
  29. <h2 className='App-title'>Welcome to React Plan</h2>
  30. </div>
  31. <div>
  32. <Router history = {history}>
  33. <div className="contentBox">
  34. <ul className="nav">
  35. <li><Link to="/">首页</Link></li>
  36. <li><Link to="/plan">计划表</Link></li>
  37. <li><Link to="/test">二级路由</Link></li>
  38. </ul>
  39. <div className="content">
  40. <Route exact path="/" component={Home}/>
  41. <Route path="/plan" component={Plan}/>
  42. <Route path="/test" component={TestRouter}/>
  43. <Route path="/detail/:id" component={Detail}/>
  44. </div>
  45. </div>
  46. </Router>
  47. </div>
  48. <Popup/>
  49. </div>
  50. </Provider>
  51. );
  52. }
  53. }
  54.  
  55. export default App

然后在 plan.js连接 store

src/component/plant.js

  1. import React,{ Component } from 'react'
  2. import { connect } from 'react-redux';
  3. import store from '../redux/store.js';
  4. // 引入 定义的 action
  5. import {show,deletePlan} from '../actions/plan.js';
  6.  
  7. class Plan extends Component {
  8. constructor(props) {
  9. super(props);
  10. }
  11. // 显示弹出
  12. show () {
  13. let b = this.props.planlist.show;
  14. store.dispatch(show(!b));
  15. }
  16. // 删除计划
  17. delete (id) {
  18. store.dispatch(deletePlan(id));
  19. }
  20. // js 跳转路由
  21. detail (id) {
  22. this.props.history.push(`/detail/${id}`)
  23. }
  24. render () {
  25. return (
  26. <div>
  27. <div className="plant">
  28. <h3>计划表</h3>
  29. <p onClick={this.show.bind(this)}>添加计划</p>
  30. </div>
  31. <table className="planlist">
  32. <thead>
  33. <tr>
  34. <th>标题</th>
  35. <th>操作</th>
  36. </tr>
  37. </thead>
  38. <tbody>
  39. {
  40. this.props.planlist.planlist.map((item,index) => {
  41. return (
  42. <tr key={index}>
  43. <td className="plan-title" onClick={this.detail.bind(this,item.id)}>{item.title}</td>
  44. <td className="plan-delect" onClick={this.delete.bind(this,item.id)}>删除</td>
  45. </tr>
  46. )
  47. })
  48. }
  49. </tbody>
  50. </table>
  51. </div>
  52. )
  53. }
  54. }
  55.  
  56. const mapStateToProps = function(store) {
  57. return {
  58. planlist: store.planlist
  59. };
  60. };
  61. // 连接 store,作为 props
  62. export default connect(mapStateToProps)(Plan);

同理下面的 js,都是用这个模块连接

src/component/detail.js

  1. import React,{ Component } from 'react'
  2. import { connect } from 'react-redux';
  3. import store from '../redux/store.js';
  4.  
  5.  
  6. class Detail extends Component {
  7. constructor(props) {
  8. super(props);
  9. // 根据路由 id 跟 store 做过滤
  10. let item = props.planlist.planlist.filter((data) => data.id == props.match.params.id)
  11. console.log(item)
  12. this.state = {
  13. plan: item[0]
  14. }
  15. }
  16. render() {
  17. return (
  18. <div style={{padding: '20px'}}>
  19. <h3>计划详情</h3>
  20. <p>id {this.state.plan.id}</p>
  21. <p>标题 {this.state.plan.title}</p>
  22. <p>内容 {this.state.plan.content}</p>
  23. </div>
  24.  
  25. )
  26. }
  27. }
  28.  
  29.  
  30. const mapStateToProps = function(store) {
  31. return {
  32. planlist: store.planlist
  33. };
  34. };
  35. // 连接 tore 和组件
  36. export default connect(mapStateToProps)(Detail);

src/component/popup.js

  1. import React,{ Component } from 'react'
  2. import { connect } from 'react-redux';
  3. import store from '../redux/store.js';
  4. import {show,addPlan} from '../actions/plan.js';
  5.  
  6. class Pupop extends Component{
  7. constructor (props) {
  8. super(props)
  9. this.state = {
  10. id: '',title: '1',content: '1'
  11. }
  12. }
  13. // 取消按钮操作
  14. close () {
  15. let b = this.props.planlist.show;
  16. this.setState({
  17. id: '',title: '',content: ''
  18. })
  19. store.dispatch(show(!b));
  20. }
  21. // 输入框事件
  22. handleChage (str,e) {
  23. this.setState({
  24. id: Math.ceil(Math.random()*10000),[str]: e.target.value
  25. })
  26. }
  27. // 确认操作
  28. conform () {
  29. store.dispatch(addPlan(this.state));
  30. this.setState({
  31. id: '',content: ''
  32. })
  33. this.close();
  34. }
  35.  
  36. render() {
  37. let self = this;
  38. return (
  39. <section className="popup" style={this.props.planlist.show ? {} : {display: 'none'}}>
  40. <div className="pBox">
  41. <span className="close" onClick={this.close.bind(this)}>X</span>
  42. <div>
  43. <h4>计划标题</h4>
  44. <input onChange={this.handleChage.bind(this,'title')} value={this.state.title} placeholder="请输入计划标题"/>
  45. </div>
  46. <div>
  47. <h4>计划内容</h4>
  48. <textarea onChange={this.handleChage.bind(this,'content')} value={this.state.content} placeholder="请输入计划内容" rows="3"></textarea>
  49. </div>
  50. <div className="pBtn">
  51. <span onClick = {this.close.bind(this)}>取消</span>
  52. <span onClick = {this.conform.bind(this)}>确认</span>
  53. </div>
  54. </div>
  55. </section>
  56. )
  57. }
  58. }
  59.  
  60. const mapStateToProps = function(store) {
  61. return {
  62. planlist: store.planlist
  63. };
  64. };
  65. // 连接 store和组件
  66. export default connect(mapStateToProps)(Pupop);

完工。github地址

猜你在找的React相关文章