react+antd+redux实现简易todolist

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Zhooson/article/details/82787350

文件夹介绍:
在这里插入图片描述

本次需要 ’ yarn add redux antd ’

  1. TodoList.js 文件
import React, { Component } from 'react'
import { Input, Button, List } from 'antd';
import 'antd/dist/antd.css';
import store from './store'	

class TodoList extends Component {
  constructor(props) {
    super(props);
    // 从store中获取数据
    this.state = store.getState()
    store.subscribe(this.storeChangeHandler)
  }
	render() {
		return (
				<div>
					<Input placeholder="请输入内容" 
						value={this.state.inputValue} 
						style={{width:300}} 
						onChange={this.getInputValueHandler}/>
					<Button type="Primary" onClick={this.addHandler}>ADD</Button>
			   	<List
			   	  style= {{width:'300px'}}
			      bordered
			      dataSource={this.state.list}
			      renderItem={(item,index) => (
			      <List.Item onClick={this.delHandler.bind(this,index)}>{item}</List.Item> )}/>
				</div>
		)
	}
	// 获取输入框数据
	getInputValueHandler=(e)=>{
		const action = {
			type: 'CHANGE_INPUT_VALUE',
			value: e.target.value
		}
		store.dispatch(action)
	}
	// 新增数据
	addHandler=()=> {
     	const action = {
			type: 'ADD_TODOLIST',
		}
		store.dispatch(action)
	}
	delHandler(index){
		console.info('index',index)
		const action = {
			type: 'DELETE_TODOLIST',
			index: index
		}
		store.dispatch(action)
	}
	// 事件监听器 
	storeChangeHandler =()=>{
		this.setState(store.getState())
	}
}
export default TodoList

  1. index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';
ReactDOM.render(<TodoList />, document.getElementById('root'));
  1. store/index.js
import { createStore } from 'redux'
import reducer from './reducer.js'

const store = createStore(
	reducer,
	// 需要安装redux的chrome的插件 下面这句话才能起作用
	window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)

export default store;
  1. store.reducer.js
// 默认的state的数据
const defaultState = {
	inputValue: '',
	list: [1, 2]	
}
// reducer 只能接受state,但不是修改state
export default (state=defaultState, action) => {
	// console.info(state,action)
	switch (action.type) {
		case 'CHANGE_INPUT_VALUE':
			return Object.assign({}, state, {
				inputValue: action.value
			})

		case 'ADD_TODOLIST':
			return Object.assign({}, state, {
				list: [...state.list, state.inputValue],
				inputValue: ''
			})
			
		case 'DELETE_TODOLIST': 
			const newState = Object.assign({}, state)
			newState.list.splice(action.index, 1)
			return newState
			
		default:
			return state
	}
}

猜你喜欢

转载自blog.csdn.net/Zhooson/article/details/82787350
今日推荐