Redux的简单用法

Redux简单的一个小实例

import React from 'react';
import { createStore } from 'redux';

const initState = [
    {
        id: 1,
        text: 'test1'
    }
];

const reducer = function(state = initState, action) {
    switch(action.type) {
        case 'ADD_TODO':
            return [
                ...state,
                action.payload
            ]
        default:
            return state;
    }
}

const store = createStore(reducer);


class Index extends React.Component {

    constructor() {
        super();
        this.state = {
            todos: [],
            val: ''
        }
    }

    temp = null;

    componentDidMount() {
        this.setState({
            todos: store.getState()
        });
        this.temp = store.subscribe(() => {
            this.setState({
                todos: store.getState()
            });
        });
    }

    componentWillUnmount() {
        this.temp();
    }

    handleChangeVal = (e) => {
        this.setState({
            val: e.target.value
        });
    }

    handleEnter = (e) => {
        if(e.keyCode === 13) {
            const val = e.target.value;
            const action = {
                type: 'ADD_TODO',
                payload: {
                    id: val,
                    text: val
                }
            };
            store.dispatch(action);
        }
    }

    render() {
        const { val } = this.state;
        return (
            <div>
                <h1>Redux的使用实例</h1>
                <input value={val} onChange={this.handleChangeVal} onKeyUp={this.handleEnter}  />
                <ul>
                    {
                        this.state.todos.map((item, index) => {
                            return (
                                <li key={index}>{item.text}</li>
                            )
                        })
                    }
                </ul>
            </div>
        )
    }
}

export default Index;
    原文作者:木子
    原文地址: https://segmentfault.com/a/1190000020057186
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞