如何在React setState()方法中更新列表?

时间:2020-01-30 06:04:02

标签: reactjs

假设我有以下React组件。

class Blog extends React.Component {
    state = { list: [] }

    addPost = () => {
        let postInfo = {
            authorName: document.getElementById('authorName').value,
            postTitle: document.getElementById('postTitle').value,
            postArea: document.getElementById('postArea').value,
        }

        let newList = [];
        newList.push(postInfo);

        this.setState({
           list: [this.state.list,...newList]
        })

        console.log(this.state.list);
        console.log(newList);
    }

    render() {
        return (
            <div>
                <h1>Welcome to My Blog</h1>
                <label>Enter Your Name</label> <br/>
                <input type="text" id="authorName"/> <br/>
                <label>Enter Post Title</label> <br/>
                <input type="text" id="postTitle"/> <br/>
                <label>Write Post</label> <br/>
                <textarea rows="4" cols="50" id="postArea"></textarea> <br/>
                <button onClick={this.addPost}>Add Post</button>
                <section id="blogArea"></section>
            </div>
        )
    }
}

我想要的是使用适当的数据输入各个字段,然后将它们添加到对象数组中,然后将该数组呈现为表格(我在这里不添加此部分)。但是问题是当我单击按钮并在控制台上记录this.state.list数据时,它显示了一个空列表。

我不知道我的代码有什么问题。如何解决此问题并以正确的方式显示数据?

2 个答案:

答案 0 :(得分:3)

不建议您采用实现方式。我已经更新了组件。请参阅小提琴以获取工作示例Check fiddle

import React from 'react';
class Blog extends React.Component {
 initialForm={
   authorName:'',
  postTitle:'',
  postArea:'',
  id:1
 }
  constructor(){
    super();
    this.state = { 
      list:[
        this.initialForm
      ]
      }
    this.addPost = this.addPost.bind(this);
    this.setFormValue = this.setFormValue.bind(this);
    this.addForm = this.addForm.bind(this);
    this.removeForm = this.removeForm.bind(this);
  }

  addForm =() =>{
    const{list} = this.state;
    const form = {
      ...this.initialForm,
      id:Number(list[list.length -1].id) +1
    }
    list = [...list, form];
    this.setState({
      list
    })
  }

  addPost = () => {
    const {list} = this.state;
      console.log(list)
  }

  setFormValue = (e, index)=>{
    const {list} = this.state;
    list[index][e.target.name] = e.target.value
    this.setState({
      list
    })
  }

removeForm=index=>{
  const {list}= this.state;
  if(list.length > 1){
    list.splice(index, 1);
    this.setState({list})
  }
}

    render() {
          const {list} = this.state;
        return (
          <>
            <div>
                <h1>Welcome to My Blog</h1>
                {list && list.map((form, index)=>(
                  <div className="form-container" key={form.id}>
                  <span className="form-count">Form Id {form.id}</span>
                  <button type="button" className="form-remove" onClick={()=> this.removeForm(index)}></button>
                  <br />
                  <label>Enter Your Name</label> <br/>
                  <input type="text" name="authorName"  onChange={(e)=>this.setFormValue(e, index)}/> <br/>
                  <label>Enter Post Title</label> <br/>
                  <input type="text" name="postTitle" onChange={(e)=>this.setFormValue(e, index)}/> <br/>
                  <label>Write Post</label> <br/>
                  <textarea rows="4" cols="50" name="postArea" onChange={(e)=>this.setFormValue(e, index)}></textarea> <br/>

                  <section id="blogArea"></section>
                </div>
                ))}
            </div>

            <div>
            <br />
            <button onClick={this.addPost}>Add Post</button>

            <br />
            <button type="button" onClick={this.addForm}>Add Form</button>
            </div>
            </>
        )
    }
}

export default Blog

答案 1 :(得分:2)

您需要使用传播运算符组合数组:

this.setState({
    list: [...this.state.list,...newList]
})