【发布时间】:2019-10-27 20:12:59
【问题描述】:
当我调用createTodo 函数时,this.state.todos 被添加到新的待办事项中。具有time 属性的对象想要移动到对象select 中的times 数组,但是times 却翻了一番。
我认为责任在于 .slice 方法和复制数组。如何绕过它?
待办事项
class Todo extends Component {
render() {
return (
<li>
<div>
{this.props.todo.description}
</div>
</li>
)
}
}
应用
class App extends React.Component {
constructor() {
super();
this.state = {
todos: [
{
time: '00:00:10',
description: 'Hello'
},
{
time: '00:00:20',
description: 'World'
}
],
todo: {
'time': '00:00:30',
'description': 'W'
},
select: {
"times": [{ 'time': '00:00:40' }, { 'time': '00:00:50' }],
"description": " ytytyty",
"id": 3,
"title": "gfgfgfgfgf"
}
};
}
addTodo = (todo) => {
const news = this.state.todos.slice();
news.push(this.state.todo);
this.setState({ todos: news });
};
render() {
this.state.todos.forEach(t => {
if (t.time) this.state.select.times.push({
time: t.time
})
});
console.log(this.state.todos);
console.log(this.state.select);
return (
<div>
<ul>
{
this.state.todos
.map((todo, index) =>
<Todo
key={index}
index={index}
todo={todo}
/>
)
}
</ul>
<button onClick={this.createTodo}>button</button>
</div>
);
}
console.log(this.state.select) -> return-->
times: [
{time: "00:00:40"}
{time: "00:00:50"}
{time: "00:00:10"} //repeat
{time: "00:00:20"} //repeat
{time: "00:00:10"}
{time: "00:00:20"}
{time: "00:00:30"}
title: "gfgfgfgfgf"
]
预期效果:
times: [
{time: "00:00:40"}
{time: "00:00:50"}
{time: "00:00:10"}
{time: "00:00:20"}
{time: "00:00:30"}
title: "gfgfgfgfgf"
]
演示 https://stackblitz.com/edit/react-jfkwnu
组件加载后应该是:selectTodo: {"times": [{'time': '00: 00: 40 '}, {' time ':' 00: 00: 50 '}], "description": "ytytyty", "id": 3, "title": "gfgfgfgfgf"}
第一次点击按钮:-> selectTodo: {times: [{time: "00:00:40"} {time: "00:00:50"} {time: "00:00:10"} {time: " 00:00:20 "} {time:" 00:00:30 "} title:" gfgfgfgfgf "]," description ":" ytytyty "," id ": 3," title ":" gfgfgfgfgf "}
二次点击按钮变化->selectTodo: {times: [{time: "00:00:40"} {time: "00:00:50"} {time: "00:00:10"} {time: "00 : 00: 20 "} {'time': '00: 00: 30'}, {time:" 00:00:30 "} title:" gfgfgfgfgf "]" description ":" ytytyty "," id ": 3 , "title": "gfgfgfgfgf"}
【问题讨论】:
-
你给出的预期效果例子是不是有错误?
-
@dashdashzako。没有错误。我认为问题在于方法切片(复制新数组)
-
@dashdashzako 你删除了你的答案吗?
-
是的,我想我错过了一些东西。如果您推送
todos而不清空它,它的值将始终推送到times,这是意料之中的。你能澄清一下 todos 是否应该持续存在,或者是否可以在每次addTodo调用之间清空? -
@dashdashzako 你能举个例子吗?我想看看它是如何工作的
标签: javascript arrays reactjs ecmascript-6 javascript-objects