1 /** 2 * index.js 3 */ 4 import React from 'react' 5 import ReactDOM from 'react-dom' 6 import TodoList from './todoList' 7 import { Provider } from './store' 8 const App = ( 9 <provider store={store}> 10 <TodoList/> 11 </provider> 12 ) 13 ReactDOM.render(App, documnet.getElementById('root')); 14 // -----------------分割線------------------------------------------------------------------------------ 15 16 /** 17 * TodoList組件 18 */ 19 import React, { Component } from 'react'; 20 import { connect } from 'react-redux'; // 引用react-redux這個對象中的一個屬性,要使用解構賦值,用花括號包裹 21 22 const TodoList = (props) => { 23 const { inputValue, list, handleInputChange, handleClick, handleDelete } = props 24 render() { 25 return ( 26 <div> 27 <div> 28 <input value={inputValue} onChange= {handleInputChange}/> 29 <button onClick={handleClick}>提交</button> 30 </div> 31 <ul> 32 { 33 this.porps.list.map((item,index)=>{ 34 return <li onClick = {() => { handleDelete(index) }} key={index}>{item}</li> 35 }) 36 } 37 </ul> 38 </div> 39 ) 40 } 41 } 42 // mapStateToProps ==> 把store中的state數據映射到組件中的props裏面 43 const mapStateToProps = (state) => { 44 return { 45 inputValue: state.inputValue, 46 list: state.list 47 } 48 } 49 // mapStateToProps ==> 把store中的state數據映射到組件中的props裏面 50 const mapDispatchToProps = (dispatch) => { 51 return { 52 handleInputChange (e) { 53 const action ={ 54 type: 'change_input_value', 55 value: e.target.value 56 } 57 dispatch(action) 58 console.log(e.target.value) 59 }, 60 handleClick () { 61 const action ={ 62 type: 'add_todolist_item' 63 } 64 dispatch(action) 65 }, 66 handleDelete (index) { 67 const action = { 68 type: 'delete_todolist_item', 69 index 70 } 71 dispatch(action) 72 } 73 } 74 } 75 76 export default connect(mapStateToProps,mapDispatchToProps)(TodoList) 77 78 // -------------------分割線--------------------------------------------------------------------------- 79 80 /** 81 * reducer.js 82 */ 83 const defaultState = { 84 inputValue: '' , 85 list: [] 86 } 87 export default (state= defaultState, action) => { 88 if( action.type === 'change_input_value') { 89 const newState = JSON.parse(JSON.stringify(state)); 90 newState.inputValue = action.value; 91 return newState 92 } 93 if ( action.type === 'add_todolist_item') { 94 const newState = JSON.parse(JSON.stringify(state)); 95 newState.list.push(newState.inputValue) 96 newState.inputValue = '' 97 return newState 98 } 99 if ( action.type === 'delete_todolist_item') { 100 const newState = JSON.parse(JSON.stringify(state)); 101 newState.list.splice(action.index, 1) 102 return newState 103 } 104 return state 105 }