javascript 如何在 React 中添加到状态数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48795792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add to state array in React
提问by Usman
I am making a simple to-do list app in React. I have 3 states, inputText (the task the user enters), triggerAnimation(to trigger animations), and tasks (the list of tasks user has entered). However I don't know how to update the tasks state (which is an array) to push the new tasks. Here is the code.
我正在 React 中制作一个简单的待办事项列表应用程序。我有 3 个状态,inputText(用户输入的任务)、triggerAnimation(触发动画)和任务(用户输入的任务列表)。但是我不知道如何更新任务状态(这是一个数组)来推送新任务。这是代码。
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
inputText: '',
triggerAnimation: '',
tasks: []
}
}
//The function triggered by button which sends the task the user has entered to the tasks array state:
addItem() {
document.querySelector("#textfield1").value = ""
this.setState({
triggerAnimation: 'fadein', tasks:
this.state.inputText
})
}
render() {
//Where User enters task:
return (
<div className="App">
<main>
<div className="enterTask">
<input type="text" className="inputclass" id="textfield1"
placeholder='Enter a task.'
onChange={event => this.setState({
inputText: event.target.value })}
onKeyPress={event => {
if(event.key === 'Enter') {
this.addItem();
}
}}
/>
<br />
<br />
<button className="button"
onClick={() => this.addItem()} data-
toggle='fadein' data-target='list'>+
</button>
</div>
<!-- Where tasks will appear: -->
<div className="log">
<p className='list'>
<span class={this.state.triggerAnimation}>
{this.state.tasks}
</span>
</p>
<button className="button">-</button>
</div>
</main>
</div>
)
}
}
export default App;
采纳答案by Shanon Hymanson
Seems like what you want is this..
好像你想要的是这个..
addItem() {
document.querySelector("#textfield1").value = ""
this.setState({
triggerAnimation: 'fadein',
tasks: this.state.tasks.concat(this.state.inputText)})
}
回答by Aaron Beall
However I don't know how to update the tasks state (which is an array) to push the new tasks.
但是我不知道如何更新任务状态(这是一个数组)来推送新任务。
Probably the cleanest way to "push to an array" in state is to use ES6 array spread. The best practice would also be to use the setStatecallback syntaxto ensure the correct state is committed before you push the new task:
在 state 中“推送到数组”的最简洁方法可能是使用ES6 数组 spread。最佳实践也是使用setState回调语法来确保在推送新任务之前提交正确的状态:
this.setState(prevState => ({
tasks: [...prevState.tasks, newTask]
}));
回答by Alex Fallenstedt
You can use .concatmethod to create copy of your array with new data:
您可以使用.concat方法使用新数据创建数组的副本:
addTask() {
this.setState({tasks: this.state.tasks.concat(["new value"])})
}
You also need to bind thisto addTaskin your constructor:
您还需要在构造函数中绑定this到addTask:
this.addTask = this.addTask.bind(this)
this.addTask = this.addTask.bind(this)
See my example:
看我的例子:
https://jsfiddle.net/69z2wepo/103069/
https://jsfiddle.net/69z2wepo/103069/
Documentation: https://reactjs.org/docs/react-component.html#setstate
回答by Fadi Quader
try this
试试这个
import React from 'react';
class Todo extends React.Component {
constructor(props) {
super();
this.state = {
value: '',
items: []
}
}
onChange = e => this.setState({ value: e.target.value })
onEnter = e => {
if(e.charCode !== 13) return;
this.addItem();
};
onClick = e => {
this.addItem()
};
addItem = () => {
const { value } = this.state;
if(!!value.trim()) return;
this.setState(prev => ({ items: [...prev.items, value], value: '' }))
};
render() {
const { value } = this.state
return (
<div>
<div>
<input
type="text"
value={value}
name="abc"
onChange={this.onChange}
onKeyPress={this.onEnter}
/>
</div>
<button onClick={this.onClick}>Add</button>
</div>
)
}
}
回答by shaunhusain
FTFY better to just use comments in the code, regarding the problem(s) you want to get the tasks array then can concat the stuff to get a new array.
FTFY 最好只在代码中使用注释,关于您想要获取任务数组的问题,然后可以连接这些内容以获取新数组。
setState({tasks:this.state.tasks.concat([this.state.inputText])})
setState({tasks:this.state.tasks.concat([this.state.inputText])})
Wouldn't hurt to clean up the code some too... learning react myself the book "the road to learning react" has some good tips on how to set things up to be a bit more readable.
清理代码也没什么坏处... 自己学习反应这本书“学习反应的道路”有一些关于如何将事情设置得更具可读性的好技巧。
Edit actually put the right code here now...
编辑实际上现在把正确的代码放在这里......
回答by Varinder
With react, you're almost always going to have to store form field information in state (controlled components) so, how about turning todo task input field into a controlled component, like so:
使用 react,您几乎总是必须将表单字段信息存储在状态(受控组件)中,因此,如何将 todo 任务输入字段转换为受控组件,如下所示:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
inputText: '',
triggerAnimation: '',
tasks: []
}
this.onInputChange = this.onInputChange.bind(this);
this.onInputKeyPress = this.onInputKeyPress.bind(this);
this.addItem = this.addItem.bind(this);
}
onInputChange(e) {
this.setState({ inputText: e.target.value });
}
onInputKeyPress(e) {
if (e.key === "Enter") {
this.addItem();
}
}
addItem() {
const itemToAdd = this.state.inputText;
const tasks = this.state.tasks;
this.setState({
inputText: "",
tasks: tasks.concat(itemToAdd);
});
}
render() {
const { inputText } = this.state;
return(
<div>
<input type="text" className="inputclass" id="textfield1" placeholder='Enter a task.'
value={inputText} onChange={this.onInputChange} onKeyPress={this.onInputKeyPress} />
<br />
<br />
<button className="button" onClick={this.addItem} data-
toggle='fadein' data-target='list'>+</button>
</div>
);
}
}
Notice how input state is controlled via component state
注意如何通过组件状态控制输入状态

