为什么todos
我的 redux 存储中有重复的嵌套对象?
组件/todoInput.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import actions from '../../actions';
class TodoInput extends Component {
constructor(props) {
super(props);
this.state = {
inputText: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange(e) {
this.setState({
inputText: e.target.value
});
}
handleClick(e) {
e.preventDefault();
this.props.dispatch(actions.addTodo(this.state.inputText));
}
render() {
return (
<div>
<input
type="text"
placeholder="todo"
value={this.state.inputText}
onChange={this.handleChange}
/>
<button onClick={this.handleClick}>Sumbit</button>
</div>
);
}
}
TodoInput.propTypes = {
dispatch: PropTypes.func,
};
export default TodoInput;
减速器/ todo.js
import { ADD_TODO } from '../constants/actionTypes';
function getId(state) {
return state.todos.reduce((maxId, todo) => {
return Math.max(todo.id, maxId);
}, -1) + 1;
}
const initialState = {
todos: [{
id: 0,
text: 'Initial Todo',
completed: false
}]
};
export default function todos(state = initialState, action) {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [{
text: action.text,
completed: false,
id: getId(state)
}, ...state.todos]
};
default:
return state;
}
}
您自己提供了嵌套结构。todos reducertodos
在 state 对象中创建一个键,并且您提供了一个初始值:
todos: [{
id: 0,
text: 'Initial Todo',
completed: false
}]
所以,这个reducer创建的状态切片是:
todos: {
todos: [{ ... }]
}
只需将初始状态声明为数组而不是带有todos
键的对象。听起来这就是你想要的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句