React-Redux小运用(一)-React_Redux_Appointment

React-Redux-Appointment

先来一波硬广:我的博客迎接旅行:传送门
这个小运用运用Create React App建立,演示地点:https://liliang-cn.github.io/react_redux_appointment,repo地点:https://github.com/liliang-cn/react_redux_appointment

这是之前的React_appointment的Redux版,之前的演示,改写自Lynda的课程Building a Web Interface with React.js

文件构造

终究的文件目次以下:

react_redux_appointment/
  README.md
  node_modules/
  package.json
  public/
    index.html
    favicon.ico
  src/
    actions/
      index.js
    components/
      AddForm.js
      AptList.js
      Search.js
      Sort.js
    constants/
      index.js
    containers/
      AddForm.js
      App.js
    reducers/
      apts.js
      formExpanded.js
      index.js
      openDialog.js
      orderBy.js
      orderDir.js
      query.js
    index.css
    index.js

用到的模块

{
  "name": "react_redux_appointment",
  "version": "0.1.0",
  "private": true,
  "homepage": "https://liliang-cn.github.io/react_redux_appointment",
  "devDependencies": {
    "react-scripts": "0.8.4"
  },
  "dependencies": {
    "axios": "^0.15.3",
    "gh-pages": "^0.12.0",
    "lodash": "^4.17.2",
    "material-ui": "^0.16.5",
    "moment": "^2.17.1",
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-redux": "^5.0.1",
    "react-tap-event-plugin": "^2.0.1",
    "redux": "^3.6.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "deploy": "yarn build && gh-pages -d build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

一切的state

小运用一共有六个状况,个中的formExpanded和openDialog是界面组件的状况,
剩下的四个离别是apts(代表一切的预定)、orderBy(依据什么来分列预定列表,依据姓名照样依据日期)、
orderDir(分列列表的方向,是增序照样降序)、query(搜刮的关键字)。

一切的Action

在运用中能够发生的actions有七种:

  • addApt,即新建预定

  • deleteApt, 即删除预定

  • toggleDialog, 即显现、隐蔽正告框

  • toggleFormExpanded, 显现/隐蔽表单

  • query,即查询

  • changeOrderBy,即转变排序的关键字

  • changeOrderDir, 即转变排序方向

定义七个常量来代表这些action的范例:

constants/index.js:

export const ADD_APT = 'ADD_APT';

export const DELETE_APT = 'DELETE_APT';

export const TOGGLE_DIALOG = 'TOGGLE_DIALOG';

export const TOGGLE_FORM_EXPANDED = 'TOGGLE_FORM_EXPANDED';

export const QUERY = 'QUERY';

export const CHANGE_ORDER_BY = 'CHANGE_ORDER_BY';

export const CHANGE_ORDER_DIR = 'CHANGE_ORDER_DIR';

actions/index.js:


import {
    ADD_APT,
    DELETE_APT,
    TOGGLE_DIALOG,
    TOGGLE_FORM_EXPANDED,
    QUERY,
    CHANGE_ORDER_BY,
    CHANGE_ORDER_DIR
} from '../constants';

export const addApt = (apt) => ({
    type: ADD_APT,
    apt
});

export const deleteApt = (id) => ({
    type: DELETE_APT,
    id
});

export const toggleDialog = () => ({
    type: TOGGLE_DIALOG
});

export const toggleFormExpanded = () => ({
    type: TOGGLE_FORM_EXPANDED
});

export const query = (query) => ({
    type: QUERY,
    query
});

export const changeOrderBy = (orderBy) => ({
    type: CHANGE_ORDER_BY,
    orderBy
});

export const changeOrderDir = (orderDir) => ({
    type: CHANGE_ORDER_DIR,
    orderDir
});

UI组件

款式

运用Material-UI须要引入Roboto字体:

src/index.css

@import url('https://fonts.googleapis.com/css?family=Roboto:300,400,500');
body {
  margin: 0;
  padding: 0;
  font-family: Roboto, sans-serif;
}

表单组件

components/addForm.js:

import React from 'react';

import {Card, CardHeader, CardText} from 'material-ui/Card';
import TextField from 'material-ui/TextField';
import DatePicker from 'material-ui/DatePicker';
import TimePicker from 'material-ui/TimePicker';
import RaisedButton from 'material-ui/RaisedButton';
import Paper from 'material-ui/Paper';
import Divider from 'material-ui/Divider';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';

import moment from 'moment';

const paperStyle = {
  width: 340,
  margin: '0 auto 20px',
  textAlign: 'center'
};

const buttonStyle = {
    margin: 12
};

// open, toggleDialog是两个布尔值,handleAdd,formExpanded, toggleFormExpanded是三个回调函数,来自于../containers/AddForm.js中的容器从store中猎取并通报下来的
const AddForm = ({handleAdd, open, toggleDialog, formExpanded, toggleFormExpanded}) => {
    let guestName, date, time, note;
    // 点击Add时会先起首搜检是不是一切的值都有输入,假如输入合轨则提议ADD_APT的action然后提议切换表单显现的action,假如输入有误则提议TOGGLE_DIALOG的action
    const onAdd = () => {
        guestName && date && time && note
        ?
        handleAdd({guestName, date, time, note}) && toggleFormExpanded()
        :
        toggleDialog()
    };

    // 这两个函数用来猎取输入的日期和时刻
    const handleDateChange = (event, aptDate) => {
        date = moment(aptDate).format('YYYY-MM-DD')
    };

    const handleTimeChange = (event, aptTime) => {
        time = moment(aptTime).format('hh:mm')
    };

    const actions = [
        <FlatButton
            label="OK"
            primary={true}
            onTouchTap={toggleDialog}
        />
    ];

    return (
        <Paper style={paperStyle} zDepth={2}>
            // Card组件的expanded的值是一个布尔值,来自于父组件传下来的formExpanded,即运用的状况formExpanded,用来肯定是不是显现表单
            <Card style={{textAlign: 'left'}} expanded={formExpanded} onExpandChange={toggleFormExpanded}>
                <CardHeader
                    title="New Appointment"
                    showExpandableButton={true}
                />
                <CardText expandable={true}>
                    <TextField
                        floatingLabelText="Guest's Name"
                        underlineShow={false}
                        onChange={e => guestName = e.target.value.trim()}
                    />
                    <Divider />
                    <DatePicker
                        hintText="Date"
                        underlineShow={false}
                        onChange={handleDateChange}
                    />
                    <Divider />
                    <TimePicker
                        hintText="Time"
                        okLabel="OK"
                        cancelLabel="Cancel"
                        underlineShow={false}
                        onChange={handleTimeChange}
                    />
                    <Divider />
                    <TextField
                        floatingLabelText="Note"
                        underlineShow={false}
                        onChange={e => note = e.target.value.trim()}
                    />
                    <Divider />
                    <RaisedButton label="Add" primary={true} style={buttonStyle} onClick={onAdd}/>
                    <RaisedButton label="Cancel" secondary={true} style={buttonStyle} onClick={toggleFormExpanded}/>
                </CardText>
                // Dialog组件的open的值也是一个布尔值,来自于父组件传下来的open,即运用的状况openDialog,用来考证表单
                <Dialog
                    title="Caution"
                    actions={actions}
                    modal={false}
                    open={open}
                    onRequestClose={toggleDialog}
                >
                    All fileds are required!
                </Dialog>
            </Card>
        </Paper>
    );
};

export default AddForm;

搜刮表单

components/Search.js:

import React from 'react';
import TextField from 'material-ui/TextField';

const Search = ({handleSearch}) => {
    return (
        <div>
            <TextField
                hintText="Search"
                onChange={
                    e => handleSearch(e.target.value)
                }
            />
        </div>
    );
};

export default Search;

分列挑选

components/Sort.js:

import React from 'react';

import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem'

const Sort = ({
    orderBy,
    orderDir,
    handleOrderByChange,
    handleOrderDirChange
}) => {
    return (
        <div>
            <SelectField
                floatingLabelText="Order By"
                value={orderBy}
                style={{textAlign: 'left'}}
                onChange={(event, index, value) => {handleOrderByChange(value)}}
            >
                <MenuItem value='guestName' primaryText="Guest's name" />
                <MenuItem value='date' primaryText="Date" />
            </SelectField>

            <SelectField
                floatingLabelText="Order Direction"
                value={orderDir}
                style={{textAlign: 'left'}}
                onChange={(event, index, value) => {handleOrderDirChange(value)}}
            >
                <MenuItem value='asc' primaryText="Ascending" />
                <MenuItem value='desc' primaryText="Descending" />
            </SelectField>
        </div>
    );
};

export default Sort;

预定列表

这个组件的作用就是显现预定列表,接收父组件传来的apts数组和handleDelete函数,在点击RaisedButton的时刻将apt.id传入handleDelete并实行。

components/AptList.js:

import React from 'react';
import {List, ListItem} from 'material-ui/List';
import {Card, CardActions, CardHeader, CardTitle, CardText} from 'material-ui/Card';
import RaisedButton from 'material-ui/RaisedButton';

const buttonStyle = {
    width: '60%',
    margin: '12px 20%',
};

const AptList = ({apts, handleDelete}) => {
    return (
        <div>
            <h2>Appointments List</h2>
            <List>
                // 这里的i也能够直接用apt.id
                {apts.map((apt, i) => (
                    <ListItem key={i}>
                        <Card style={{textAlign: 'left'}}>
                            <CardHeader
                                title={apt.date}
                                subtitle={apt.time}
                                actAsExpander={true}
                                showExpandableButton={true}
                            />
                            <CardTitle title={apt.guestName}/>
                            <CardText expandable={true}>
                                {apt.note}
                                <CardActions>
                                    <RaisedButton
                                        style={buttonStyle}
                                        label="Delete"
                                        secondary={true}
                                        onClick={() => handleDelete(apt.id)}
                                    />
                                </CardActions>
                            </CardText>
                        </Card>
                    </ListItem>
                ))}
            </List>
        </div>
    );
};

export default AptList;

处置惩罚差别的actions

处置惩罚表单的显现和隐蔽

reducers/formExpanded.js:

import { TOGGLE_FORM_EXPANDED } from '../constants';

// formExpanded默以为false,即不显现,当提议范例为TOGGLE_FORM_EXPANDED的action的时刻,将状况切换为true或许false
const formExpanded = (state=false, action) => {
    switch (action.type) {
        case TOGGLE_FORM_EXPANDED:
            return !state;
        default:
            return state;
    }
};

export default formExpanded;

表单考证毛病的提醒对话框

reducers/openDialog.js:

import { TOGGLE_DIALOG } from '../constants';

// 这个action是由其他action激发的
const openDialog = (state=false, action) => {
    switch (action.type) {
        case TOGGLE_DIALOG:
            return !state;
        default:
            return state;
    }
};

export default openDialog;

处置惩罚新建预定和删除预定

reducers/apts.js:

import { ADD_APT, DELETE_APT } from '../constants';

// 用唯一的id来标识差别的预定,也能够直接用时刻戳new Date()
let id = 0;

// 依据传入的数组和id来实行删除操纵
const apts = (state=[], action) => {
    const handleDelete = (arr, id) => {
        for(let i=0; i<arr.length; i++) {
            if (arr[i].id === id) {
                return [
                    ...arr.slice(0, i),
                    ...arr.slice(i+1)
                ]
            }
        }
    };

    switch (action.type) {
        // 依据action传入的数据apt再加上id来天生一个新的预定
        case ADD_APT:
            return [
                ...state,
                Object.assign({}, action.apt, {
                    id: ++id
                })
            ]
        case DELETE_APT:
            return handleDelete(state, action.id);
        default:
            return state;
    }
};

export default apts;

查询和分列体式格局

这三个函数的作用就是依据action传入的数据,更新state里的对应值,在这里并不会真正的去处置惩罚预定的列表。

reducers/orderBy.js:

import { CHANGE_ORDER_BY } from '../constants';

const orderBy = (state=null, action) => {
    switch (action.type) {
        case CHANGE_ORDER_BY:
            return action.orderBy
        default:
            return state;
    }
};

export default orderBy;

reducers/orderDir.js:

import { CHANGE_ORDER_DIR } from '../constants';

const orderDir = (state=null, action) => {
    switch (action.type) {
        case CHANGE_ORDER_DIR:
            return action.orderDir
        default:
            return state;
    }
};

export default orderDir;

reducers/query.js:

import { QUERY } from '../constants';

const query = (state=null, action) => {
    switch (action.type) {
        case QUERY:
            return action.query;
        default:
            return state;
    }
}

export default query;

合成reducers

reducers/index.js:

import { combineReducers } from 'redux';

import apts from './apts';
import openDialog from './openDialog';
import formExpanded from './formExpanded';
import query from './query';
import orderBy from './orderBy';
import orderDir from './orderDir';

// redux供应的combineReducers函数用来将处置惩罚差别部份的state的函数合成一个
// 每当action进来的时刻会经由每个reducer函数,然则因为action范例(type)的差别
// 只要相符(switch语句的推断)的reducer才会处置惩罚,其他的只是将state一成不变返回

const reducers = combineReducers({
    apts,
    openDialog,
    formExpanded,
    query,
    orderBy,
    orderDir
});

export default reducers;

容器组件

containers/AddForm.js:

import { connect } from 'react-redux';

import { addApt, toggleDialog, toggleFormExpanded } from '../actions';

import AddForm from '../components/AddForm';

// AddForm组件可经由历程props来猎取两个state:open和formExpanded
const mapStateToProps = (state) => ({
    open: state.openDialog,
    formExpanded: state.formExpanded
});

// 使得AddForm组件能够经由历程props获得三个回调函数,挪用即可相当于提议action
const mapDispatchToProps = ({
    toggleFormExpanded,
    toggleDialog,
    handleAdd: newApt => addApt(newApt)
});

// 运用react-redux供应的connect函数,能够将一个组件提升为容器组件,容器组件可直接猎取到state、能够直接运用dispatch。
// 这个connect函数接收两个函数作为参数,这两个作为参数的函数的返回值都是对象, 按商定他们离别命名为mapStateToProps,mapDispatchToProps
// mapStateToProps肯定了在这个组件中能够获得哪些state,这里的话只用到了两个UI相干的state:open和formExpanded,这些state都可经由历程组件的props来猎取
// mapDispatchToProps原本应该是返回对象的函数,这里比较简单,直接写成一个对象,肯定了哪些action是这个组件能够提议的,也是经由历程组件的props来猎取
// connect函数的返回值是一个函数,接收一个组件作为参数。

export default connect(mapStateToProps, mapDispatchToProps)(AddForm);

containers/App.js:

import React from 'react';
import { connect } from 'react-redux';

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import injectTapEventPlugin from 'react-tap-event-plugin';

injectTapEventPlugin();
import AppBar from 'material-ui/AppBar';
import Paper from 'material-ui/Paper';

import AddForm from '../containers/AddForm';
import Search from '../components/Search';
import Sort from '../components/Sort';
import AptList from '../components/AptList';

import { deleteApt, query, changeOrderBy, changeOrderDir } from '../actions';

const paperStyle = {
  minHeight: 600,
  width: 360,
  margin: '20px auto',
  textAlign: 'center'
};

const App = ({
  apts,
  dispatch,
  orderBy,
  orderDir,
  handleSearch,
  handleDelete,
  handleOrderByChange,
  handleOrderDirChange
}) => (
  <MuiThemeProvider>
    <div>
      <AppBar
        title="React Redux Appointment"
        showMenuIconButton={false}
      />
      <Paper style={paperStyle} zDepth={5}>
        <AddForm />
        <Search handleSearch={handleSearch}/>
        <Sort
          orderBy={orderBy}
          orderDir={orderDir}
          handleOrderByChange={handleOrderByChange}
          handleOrderDirChange={handleOrderDirChange}
        />
        <AptList
          apts={apts}
          handleDelete={handleDelete}
        />
      </Paper>
    </div>
  </MuiThemeProvider>
);


// 处置惩罚搜刮和排序,返回处置惩罚后数组
const handledApts = (apts, query, orderBy, orderDir) => {
    const filterArr = (arr, query) => {
        return arr.filter(item => (
            item.guestName.toLowerCase().indexOf(query) !== -1 ||
            item.date.indexOf(query) !== -1 ||
            item.time.indexOf(query) !== -1 ||
            item.note.toLowerCase().indexOf(query) !== -1)
        );
    };

    const sortArr = (arr, orderBy, orderDir) => {
      if (orderBy && orderDir) {
        return arr.sort((apt1, apt2) => {
          const value1 = apt1[orderBy].toString().toLowerCase();
          const value2 = apt2[orderBy].toString().toLowerCase();
            if (value1 < value2) {
                return orderDir === 'asc' ? -1 : 1;
            } else if (value1 > value2) {
                return orderDir === 'asc' ? 1 : -1;
            } else {
                return 0;
            }
        })
      } else {
        return arr;
      }
    };

    if (!query) {
      return sortArr(apts, orderBy, orderDir);
    } else {
      return sortArr(filterArr(apts, query), orderBy, orderDir);
    }
};


// App组件可经由历程props来猎取到四个state:query, orderBy, orderDir, apts
// 这里是真正处置惩罚搜刮和排序的处所,并非直接将state中的apts返回,而是挪用handleApts,返回处置惩罚的数组
const mapStateToProps = (state) => ({
    query: state.query,
    orderBy: state.orderBy,
    orderDir: state.orderDir,
    apts: handledApts(state.apts, state.query, state.orderBy, state.orderDir),
});

// App组件可经由历程props来猎取到四个函数,也就是提议四个action:handleSearch,handleDelete,handleOrderByChange,handleOrderDirChange
const mapDispatchToProps = ({
    handleSearch: searchText => query(searchText),
    handleDelete: id => deleteApt(id),
    handleOrderByChange: orderBy => changeOrderBy(orderBy),
    handleOrderDirChange: orderDir => changeOrderDir(orderDir)
});

export default connect(mapStateToProps, mapDispatchToProps)(App);

进口文件

src/index.js:

import React from 'react';
import ReactDOM from 'react-dom';

import { createStore } from 'redux';
import { Provider } from 'react-redux';

import App from './containers/App';
import './index.css';

import reducers from './reducers';

// 运用createStore示意运用的store,传入的第一个参数是reducers,第二个参数是Redux的调试东西
const store = createStore(reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

// 运用react-redux供应的Provider组件,使App组件及子组件能够获得store的相干的东西,如store.getState(),store.dispatch()等。
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

末端

React供应的是经由历程state来掌握掌握UI和单向数据活动,
Redux供应的是单一数据源和只能经由历程action和reducer来处置惩罚state的更新。

以个中的点击按钮显现新建预定表单的历程来捋一捋React、React-Redux的逻辑(灵感来源于自Cory House大神):

  • 用户:点击按钮

  • React:哈喽,action天生函数toggleFormExpanded,有人点击了睁开新建预定的表单。

  • Action:收到,谢谢React,我立时宣布一个action也就是{type:TOGGLE_FORM_EXPANDED}关照reducers来更新state。

  • Reducer:谢谢Action,我收到你的传过来要实行的action了,我会依据你通报进来的{type:TOGGLE_FORM_EXPANDED},先复制一份当前的state,然后把state中的formExpanded的值更新为true,然后把新的state给Store。

  • Store:嗯,Reducer你干得美丽,我收到了新的state,我会关照一切与我衔接的组件,确保他们会收到新state。

  • React-Redux:啊,谢谢Store传来的新数据,我如今就看看React界面是不是须要须要发生变化,啊,须要把新建预定的表单显现出来啊,那界面照样要更新一下的,交给你了,React。

  • React:好的,有新的数据由store经由历程props通报下来的数据了,我会立时依据这个数据把新建预定的表单显现出来。

  • 用户:看到了新建预定的表单。

假如以为还不错,来个star吧。(笑容)

    原文作者:可能不是苹果
    原文地址: https://segmentfault.com/a/1190000007908006
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞