首先,我知道此代码段中的很多内容已经关闭,我知道。我只是想在这里解决这个问题。
由于某种原因,我的应用程序说它无法读取未定义的属性“ todo”,并突出显示todos: [...state.todos]
。
我不导入我应该在这里的东西吗?
Form.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import uuidv1 from 'uuid';
import { addTodo } from '../actions';
import TodoInput from './todo-input';
import TodoList from './TodoList';
const mapDispatchToProps = dispatch => {
return {
addTodo: todo => dispatch(addTodo(todo))
};
};
const mapStateToProps = (state) => ({
todos: [...state.todos]
})
class ConnectedForm extends Component {
constructor(props){
super(props);
this.state = {
inputValue: ''
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleToggle = this.handleToggle.bind(this);
};
handleChange = (e) => {
e.preventDefault();
this.setState({
inputValue: e.target.value
});
}
handleSubmit = (e) => {
e.preventDefault();
const { inputValue} = this.state;
const id = uuidv1();
this.props.addTodo({inputValue, id});
this.setState({inputValue: ''});
}
handleToggle (e) {
const id = parseInt(e.target.id);
this.setState((prevState) => ({
todos: prevState.todos.map(todo => todo.id === id ? {...todo, done: !todo.done} : todo)
}));
console.log(e.target);
}
render() {
const { inputValue } = this.state;
return (
<div className='form-group'>
<TodoInput
value={inputValue}
onChange={this.handleChange}
onSubmit={this.handleSubmit}
/>
<TodoList />
</div>
);
}
}
const Form = connect(mapStateToProps, mapDispatchToProps) (ConnectedForm);
export default Form;
TodoList.js
import React, { Component } from 'react';
import TodoItem from './TodoItem';
import { removeTodo, toggleComplete } from '../actions';
import { connect } from 'react-redux';
const mapDispatchToProps = dispatch => {
return {
removeTodo: id => dispatch(removeTodo(id)),
toggleComplete: isDone => dispatch(toggleComplete(isDone))
};
};
const mapStateToProps = state => {
return {todos: [...state.todos]};
};
class List extends Component {
render() {
const mappedTodos = this.props.todos.map((todo, index) => (
<TodoItem
todo={todo}
title={todo.title}
key={index}
removeHandler={this.props.removeTodo}
toggleComplete={this.props.toggleComplete}
/>
));
return (
mappedTodos
);
}
}
const TodoList = connect(mapStateToProps, mapDispatchToProps) (List)
export default TodoList;
减速器
import { ADD_TODO, REMOVE_TODO, TOGGLE_COMPLETE } from '../constants/action-types';
import uuidv1 from 'uuid';
const initialState = {
todos: []
};
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos,
{
title: action.payload.inputValue,
id: uuidv1(),
createdAt: Date(),
priority: '',
deadline: '',
isComplete: false
}]
}
case REMOVE_TODO:
return {
...state,
todos: [...state.todos.filter(todo => todo.id !== action.payload)]
}
case TOGGLE_COMPLETE:
return (
console.log(action.payload)
)
default:
return state;
}
}
export default rootReducer;