开发者问题收集

如何将新元素从状态推送到数组中

2019-09-14
98

我尝试将元素推送到名为“this.state.tags”的数组中。在控制台上,我看到元素被推送到数组中。但是,当我添加某些内容时,数组会显示为空白,当我添加更多项目时,我只会看到之前添加的项目。我没有看到我推送的最新项目。

我已经从子组件 Grades.js 中执行了 Object.assign([], this.state.tags)。然后我推送了“this.state.newTag”,并将状态重置为新结果。

//From Grades.js, the child component

    state = {
        toggle: null,
        newTag: '',
        tags: []
    }

    addTags = (event) => {
        event.preventDefault();

        let newTagArr = Object.assign([], this.state.tags)
        newTagArr.push(this.state.newTag)

        this.setState({
            tags: newTagArr
        }) 

        // this will pass on to the parent
        this.props.filterTags(this.state.tags)
    }

    render() {
        const { tags } = this.state

        let tagList = tags.map((item, index) => {
            return (
                <li key={index} className="tagListItem">{item}</li>
            )
        })

        return(
           <div>
               <ul className="tagList">{tagList}</ul>

                        <form onSubmit={this.addTags}>
                            <input 
                                placeholder="Add a tag" 
                                name="newTag"
                                onChange={this.handleInput}
                                style={{border: '0', borderBottom: '1px solid #000'}} 
                            />
                        </form>
           </div>
        )
    }

// From App.js, the parent component

  state = {
    students: [],
    filteredStudents: [],
    filteredByTag: [],
    search: '',
    tag: '',
    toggle: false
  }

  componentDidMount() {
    axios.get('https://www.hatchways.io/api/assessment/students')
    .then(result => {

      let newArr = Object.assign([], result.data.students);
      let newResult = newArr.map(elem => {
        return {city: elem.city, company: elem.company, email: elem.email, 
          firstName: elem.firstName.toLowerCase(), lastName: elem.lastName.toLowerCase(),
          grades: elem.grades, id: elem.id, pic: elem.pic, skill: elem.skill}
      })

      this.setState({
        students: newResult
      })

    })
    .catch(err => console.log(err))
  }

  tagFiltering = (param) => {
    console.log(param)
    this.state.students.push()
  }

I expect the output to be ["tag1", "tag2", "tag3"]
Not ["tag1", "tag2"], when I've already typed in tag1, tag2 and tag3
1个回答

使用 ES2015 语法:

this.setState({
    tags: [...this.state.tags , this.state.newTag]
}) 

在 React 中,状态是 immutable 的,这意味着我们每次都必须提供新的状态对象,我们调用 setState 方法。

belSalah
2019-09-14