简体   繁体   中英

Why does it not push the element into the array state "tasks"?

I'm trying to create a todo app in React. I'm currently trying to print the input when i press the + button, but it is not working. Can anyone help to check my syntax!

 import React from 'react'; import './App.css'; class App extends React.Component { constructor(){ super(); this.state = { value: '', tasks: [] }; this.handleChange = this.handleChange.bind(this) this.addItem = this.addItem.bind(this) } handleChange(event) { this.setState({ value: event.target.value }) } addItem(){ this.state.tasks.push(this.state.value) } render(){ return( <div> <input type="text" value={this.state.value} onChange={this.handleChange}></input> <button onClick={this.addItem}>+</button> <button>-</button> <h1>{this.state.tasks}</h1> </div> ) } } export default App;

To change the state you should use this.setState . Refer to https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly . Reading React documentation might save you a lot of time overall.

Modifying state directly is not the correct way!

instead use setState:

this.setState({
  tasks: this.state.tasks.concat(this.state.value)
})

You need to setState task

addItem() {
    const newTask = [this.state.value, ...this.state.tasks];
    this.setState({ tasks: newTask });
    this.setState({ value: "" });
  }

enter image description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM