React第三方组件5(状态管理之Redux的使用②TodoList上)

时间:2022-05-08
本文章向大家介绍React第三方组件5(状态管理之Redux的使用②TodoList上),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本教程总共6篇,每日更新一篇,请关注我们!你可以进入历史消息查看以往文章,也敬请期待我们的新文章!

1、React第三方组件5(状态管理之Redux的使用①简单使用)---2018.03.20

2、React第三方组件5(状态管理之Redux的使用②TodoList上)---2018.03.21

3、React第三方组件5(状态管理之Redux的使用③TodoList中)---2018.03.22

4、React第三方组件5(状态管理之Redux的使用④TodoList下)---2018.03.23

5、React第三方组件5(状态管理之Redux的使用⑤异步操作)---2018.03.26

6、React第三方组件5(状态管理之Redux的使用⑥Redux DevTools)---2018.03.27

开发环境:Windows 8,node v8.9.1,npm 5.5.1,WebStorm 2017.2.2

1、先把redux1复制一份为redux2,并在路由里添加

import React from 'react';
import {HashRouter, Route, NavLink, Redirect} from 'react-router-dom';
import Redux1 from './redux1/Index'
import Redux2 from './redux2/Index'

const Index = ({match}) =>
    <HashRouter>
        <div>
            <div className="nav">
                <NavLink to="/Redux/Redux1" activeClassName="selected">Redux1</NavLink>
                <NavLink to="/Redux/Redux2" activeClassName="selected">Redux2</NavLink>
            </div>
            <Route exact path={`${match.url}`}
                   render={() => (<Redirect to={`${match.url}/Redux1`}/>)}/>
            <Route path={`${match.url}/Redux1`} component={Redux1}/>
            <Route path={`${match.url}/Redux2`} component={Redux2}/>
        </div>
    </HashRouter>
;

export default Index;

2、编写业务代码 redux2 -> Index.jsx

import React from 'react';
import {createStore} from 'redux';
import {Provider, connect} from 'react-redux';
import reducer from './reducer'

const store = createStore(reducer);

class Index extends React.Component {
    render() {
        return (
            <div className="todoList">
                <input type="text" ref="todoInput"/>
                <button onClick={() => this.props.dispatch({type: 'ADD', title: this.refs['todoInput'].value})}>添加
                </button>
                {
                    this.props.storeState.list.map(data => <li key={data.id}>{data.title}</li>)
                }
            </div>
        );
    }
}

const mapStateToProps = state => ({storeState: state});

const Main = connect(
    mapStateToProps
)(Index);

export default () =>
    <Provider store={store}>
        <Main/>
    </Provider>
;

3.修改reducer.js

export default (state = {
    list: []
}, action)=> {
    switch (action.type) {
        /*业务模型判断*/
        case 'ADD':
            if (!action.title) {
                alert('不能为空');
                return state;
            }
            let list = state.list;
            list.push({id: state.list.length + 1, title: action.title, status: 1});
            return {list};
        default:
            return state;
    }
};

4、看下浏览器效果