import React,{Component} from 'react';
import * as uuid from 'uuid';
import { render } from '@testing-library/react';
class TodoList extends React.Component{
state={
text:''
}
onChange=(e)=>{
this.setState({
text:e.target.value,
})
}
onClick=()=>{
const id =uuid.v4();
this.props.addTodo(id,this.state.text)
}
onDelete=()=>{
this.props.deteleTodo(this.props.todos.id)}
render(){
return(
<div>
<ul>
{this.props.todos.map((todo)=>(
<li key={todo.id}>{todo.text}
<button onClick={this.onDelete}>delete</button>
</li>
)
)}
</ul>
<input value ={this.state.text} onChange= {this.onChange}/>
<button onClick={this.onClick}> Add toto</button>
</div>
)
}
}
export default TodoList
here is my actions/add-todo.js
export const addTodo =(id,text)=>({
type:'ADD_TODO',
payload:{id,text},
});
export const deteleTodo=(id)=>({
type: 'REMOVE_TODO',
payload:id
})
Here is my containers/todo-list.js
import {addTodo,deteleTodo} from '../actions/add-todo'
const mapStateToProps=(state)=>({
todos:state.todos,
})
const mapDispatchToProps=(dispatch)=>
{
return{
addTodo:(id,text)=>dispatch(addTodo(id,text)),
deteleTodo:(id)=>dispatch(deteleTodo(id))
}
}
export default connect (mapStateToProps,mapDispatchToProps)(TodoList)
here is my reducers index and todos.js
export default (state =[],action)=>{
switch (action.type){
case 'ADD_TODO':
return[...state, action.payload];
case 'REMOVE_TODO':
const newState=state.filter((todo)=>todo.id !== action.payload.id);
return newState;
default:
return state;
}
}
import {combineReducers} from 'redux'
import todosReducer from './todos'
export default combineReducers({
todos:todosReducer,
})
uj5u.com熱心網友回復:
修改了todoList組件的代碼
import React from 'react';
import * as uuid from 'uuid';
class TodoList extends React.Component{
constructor(props){
super(props)
this.onChange = this.onChange.bind(this)
this.onClick = this.onClick.bind(this)
this.onDelete = this.onDelete.bind(this)
this.state={
text:''
}
}
onChange(e)=>{
this.setState({
text:e.target.value,
})
}
onClick()=>{
const id =uuid.v4();
this.props.addTodo(id,this.state.text)
}
onDelete()=>{
this.props.deteleTodo(this.props.todos.id)
}
render(){
return(
<div>
<ul>
{this.props.todos.map((todo)=>(
<li key={todo.id}>{todo.text}
<button onClick={this.onDelete}>delete</button>
</li>
)
)}
</ul>
<input value ={this.state.text} onChange= {this.onChange}/>
<button onClick={this.onClick}> Add toto</button>
</div>
)
}
}
export default TodoList
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/59663.html
標籤:JavaScript
