无状态组件

当组件中只有一个render方法时,我们就可以把组件改造成无状态组件

无状态组件的优势:没有声明周期函数的运行,更效率。

src/TodoListUI.js

import React from 'react';
import 'antd/dist/antd.css'
import {
    Input,
    Button,
    List
} from 'antd';

const TodoListUI = (props)=>{
    return (
        <div style={{marginTop:"10px",marginLeft:'10px'}}>
            <Input 
                value = {props.inputValue}
                placeholder = 'todo info' 
                style={{width:'300px',marginRight:'10px'}}
                onChange = {props.hanldeInputChange}
            />
            <Button type='primary' onClick={props.handleButtonClick}>提交</Button>
            <List
                  bordered
                  dataSource={props.list}
                  renderItem={(item,index)=> (
                    <List.Item onClick={(index)=>{props.handleItemDelete(index)}}>
                      {item}
                    </List.Item>
                  )}
            />
        </div>
    )
}

export default TodoListUI;

src/TodoList.js

import React, { Component } from 'react';

import store from './store' //store存储了公用的数据
import {
    getInputChangeAction,
    getButtonClickAction,
    getDeleteItemAction
} from './store/actionCreator'

import TodoListUI from './TodoListUI';

class TodoList extends Component{
    constructor(props){
        super(props)
        // console.log(store.getState()); 拿到store所有数据
        this.state = store.getState();
        this.hanldeInputChange = this.hanldeInputChange.bind(this)
        this.handleStoreChange = this.handleStoreChange.bind(this)
        this.handleButtonClick = this.handleButtonClick.bind(this)
        this.handleItemDelete = this.handleItemDelete.bind(this)

        store.subscribe(this.handleStoreChange);
    }

    render(){
        const {inputValue, list} = this.state;
        return     (
                <TodoListUI 
                    inputValue = {inputValue}
                    hanldeInputChange = {this.hanldeInputChange}
                    handleButtonClick = {this.handleButtonClick}
                    list = {list}
                    handleItemDelete = {this.handleItemDelete}
                />
            )
    }

    hanldeInputChange(e){
        //action的写法也是固定的,它是一个对象
        const action = getInputChangeAction(e.target.value)
        //把action告诉store后,store会自动把prevStore和action转发给reducer,
        //接着我们就可以在reducer中接收到state和action
        store.dispatch(action)
    }

    handleStoreChange(){
        // console.log("store changed");
        this.setState(store.getState());
    }

    handleButtonClick(){
        //actio是一个对象的样子,有一个type属性
        const action = getButtonClickAction()
        store.dispatch(action)
    }

    handleItemDelete(index){
        const action = getDeleteItemAction(index);
        store.dispatch(action)
    }
}

export default TodoList;