gpt4 book ai didi

javascript - react 事件处理程序。向数组添加值

转载 作者:行者123 更新时间:2023-11-29 14:40:25 25 4
gpt4 key购买 nike

为什么你好 Javascript 奇才,

我真的开始深入研究 React,不得不说,我发现它非常有趣。但是,我在从输入表单中获取值并将其添加到数组中时遇到问题。我正在构建一个小型应用程序(我太有创意了),我试图在每次单击添加按钮时将输入字段中的值添加到数组中。

关键在于,它工作得很好,只是不是在第一次提交按钮时。例如,假设我启动应用程序,在输入字段中键入“Hello”,然后按回车键。正如您在我的代码中看到的那样,我在函数末尾设置了一个 console.log,因此每次单击按钮时我都可以看到发生了什么。

第一次单击该按钮时,我在控制台上记录的只是“[]”,在下一次单击时,我会看到我想要的内容,在那里我会看到一条日志,上面写着 [“Hello”]。我之后添加的任何其他输入都会被顺利地添加到数组中。我觉得必须有一些非常细微的事情发生,可能只需要一双经验丰富的眼睛。对于可能的解决方案的任何反馈,以及我可以改进代码的任何方式,我将不胜感激。

这是控制台的快速屏幕截图。第一次点击从 [] 部分开始。

enter image description here

import React, { Component } from 'react';
import ListItem from './list-item';

export default class App extends Component {
constructor(props) {
super(props);

this.state = { tasks: [] };
this.addTask = this.addTask.bind(this);
}

addTask(event) {
event.preventDefault();
var form = this._input.value;
var allTasks = this.state.tasks.concat([form]);
this.setState({tasks: allTasks});
console.log(this.state.tasks);
}

render() {
return (
<div className="app-main">
<div className="col-sm-12 text-center">
{/* App Title */}
<h1>Task App</h1>
<div id="formWrapper">
{/* Start of Form */}
<form onSubmit={this.addTask}>
<input ref={(el) => this._input = el} />
<button type="submit" className="btn btn-md btn-primary">Add</button>
</form>
{/* List Item */}
<ListItem tasks={this.state.tasks} />
</div>
</div>
</div>
);
}
}

最佳答案

根据文档,

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

来自 the notes section of setState , 我强调的是粗体。所以 setState 不会立即改变状态。虽然,当 setState 合并了新状态时,它总是会再次调用 render,因此 ListItem 只是不同步地获取新任务,或者也许,不是马上。

console.log 向下移动到渲染函数中,您会看到不同之处:

...
<ListItem tasks={this.state.tasks} />
{console.log(this.state.tasks)}
...

关于javascript - react 事件处理程序。向数组添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39046037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com