如何在React State的现有数组中追加新值?

时间:2018-03-27 23:04:22

标签: arrays reactjs

以下是我的组件定义。

我收到一个输入为Mistake Name,并希望将其存储在数组中并显示它。

import React, {Component} from 'react';


class AddMistake extends Component {

    constructor(props){
        super(props);
        this.state = {
            mistake: [],
            value: ''
        }
        this.handleChange = this.handleChange.bind(this);
        this.addMistake = this.addMistake.bind(this);
    }
    handleChange(event) {
        this.setState({value: event.target.value});
    }

    addMistake(event){
        this.setState({mistake: [].push(this.state.value)});
        console.log("Mistake is "+ this.state.mistake.length + " And Value is "+ this.state.value);
    }

    render(){
        return(
            <div>
                <input value={this.state.value} type='text' onChange={this.handleChange} /> 
                <button onClick={this.addMistake}> Add Mistake </button>
                <div>
                {this.state.mistake}
                </div>
                <div>{this.state.value}</div>

            </div>
        );
    }
} 

export default AddMistake;

有人可以推荐更好的方法来处理这个问题吗?

2 个答案:

答案 0 :(得分:2)

addMistake(event){
   this.setState((prevstate) => ({mistake: prevstate.mistake.concat([this.state.value]))
}); 
   console.log("Mistake is "+ this.state.mistake.length + " And Value is "+ this.state.value);
}

在渲染方法

 render(){
  return(
    <div>
     <input value={this.state.value} type='text' onChange={this.handleChange} /> 
     <button onClick={this.addMistake}> Add Mistake </button>
      <div>
       {this.state.mistake.length && this.state.mistake.map(item =><p> {item} </p>) }
      </div>
       <div>{this.state.value}</div>
     </div>
        );
    }

this.state.mistake.length检查数组中是否有任何内容。

答案 1 :(得分:0)

以下语法为我工作!谢谢@omar和@Hamms

addMistake(event){
    this.setState({mistake: this.state.mistake.concat([this.state.value])
 }); 
    console.log("Mistake is "+ this.state.mistake.length + " And Value is "+ this.state.value);
 }