Redux--用React-Redux来重构ToDoList

React-Redux 的两个核心组件:
Provider提供器
connect连接器

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import ToDoList from './ToDoList'
import {Provider} from 'react-redux'
import store from './store'
 const app=(
   <Provider store={store}>
      <ToDoList/>
   </Provider>
 )
ReactDOM.render(
  app,
  document.getElementById('root')
);

ToDoList.js

import React, { Component } from 'react';
import {connect} from 'react-redux'
import store from './store'
class ToDoList extends Component {
    constructor(props) {
        super(props);
       this.state = store.getState();
    }
    render() { 
        return ( 
            <div>
                <input value={this.props.inputValue} onChange={this.props.inputChange}/>
                <button onClick={this.props.addItem}>添加游戏</button>
                {
                    this.props.list.map((value,key)=>{
                        return <li key={key} onClick={this.props.deleteItem}>{value}</li>
                    })
                }
            </div>
         );
    }
    inputChange(e){
        console.log(e.target.value)
    }
}

const stateToProps=(state)=>{
    return {
        inputValue : state.inputValue,
        list:state.list
    }
}

const stateToDispatch=(dispatch)=>{
    return {
        inputChange(e){
            let action={
                type:'input_change',
                value:e.target.value
            }
            dispatch(action)
        },
        addItem(){
            let action={
                type:'add_item',
            }
            dispatch(action)
        },
        deleteItem(index){
            console.log(index)
            let action={
                type:'delete_item',
                value:index
            }
            dispatch(action)
        }
    }
}
 
export default connect(stateToProps,stateToDispatch)(ToDoList);

reducer.js

const defaultState={
    inputValue:'hello',
    list:[]
}
export default (state = defaultState, action)=>{
    if(action.type === 'input_change'){
        let newState = JSON.parse(JSON.stringify(state))
        newState.inputValue = action.value
        return newState
    }
    if(action.type === 'add_item'){
        let newState = JSON.parse(JSON.stringify(state))
        newState.list.push(newState.inputValue)
        newState.inputValue=''
        return newState
    }
    if(action.type === 'delete_item'){
        let newState = JSON.parse(JSON.stringify(state))
        newState.list.splice(action.value,1)
        return newState
    }
    return state
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值