1. 程式人生 > >react+antd+redux實現簡易todolist

react+antd+redux實現簡易todolist

資料夾介紹:
在這裡插入圖片描述

本次需要 ’ 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
	}
}