gpt4 book ai didi

javascript - 如何在 React 中添加到状态数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:01:11 24 4
gpt4 key购买 nike

我正在用 React 制作一个简单的待办事项列表应用程序。我有 3 种状态,inputText(用户输入的任务)、triggerAnimation(触发动画)和 tasks(用户输入的任务列表)。但是我不知道如何更新任务状态(这是一个数组)来推送新任务。这是代码。

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;

最佳答案

However I don't know how to update the tasks state (which is an array) to push the new tasks.

在状态中“推送到数组”的最干净的方法可能是使用 ES6 array spread .最佳做法也是使用 setState callback syntax确保在推送新任务之前提交正确的状态:

this.setState(prevState => ({
tasks: [...prevState.tasks, newTask]
}));

关于javascript - 如何在 React 中添加到状态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48795792/

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