如何将新元素从状态推入数组

时间:2019-09-14 13:27:23

标签: arrays reactjs

我正在尝试将元素推入名为“ 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 个答案:

答案 0 :(得分:4)

使用ES2015语法:

immutable

在反应中,状态为setState,这意味着我们每次必须提供新的状态对象,我们调用from django.contrib.sites.shortcuts import get_current_site my_current_domain = get_current_site(request) return {'domain':my_current_domain} 方法。