简体   繁体   English

Array.splice可在两个状态子数组上使用

[英]Array.splice works on both state sub-arrays

This is my simple react component. 这是我简单的react组件。 I set rooms firstly in state in componentWillReceiveProps and then on submit I do set rooms to data in state as well. 我首先在componentWillReceiveProps中将rooms设置为状态,然后在submit也将rooms设置为状态data

Also on submit I do an api call by passing single object from the rooms and when response come then I do slice that object from the data (but not from rooms ) until the data length is equal to 0 . 同样在提交时,我通过从rooms传递单个对象进行api调用,当响应到来时,我从数据(而不是从rooms )中slice该对象,直到data长度等于0为止。

Now problem is when I do slice from the data then it slices the rooms elements as well. 现在的问题是,当我做slicedata然后将其slicesrooms元素。

class EditRoom extends Component {
  constructor() {
    super()
    this.state = {
      rooms: [],
      data: []
    }
  }

  componentWillMount() {
    const { fetchRooms } = this.props
    fetchRooms()
  }

  componentWillReceiveProps(np) {
    const { rooms, setNick, setNickName } = np
    if (this.props.rooms !== rooms) {
      console.log('ppppppppppppp')
      this.setState({ rooms })
    }
    if (setNick) {
      const data = this.state.data
      data.splice(0, 1)
      this.setState({ data }, () => {
        if (data.length === 0) {
          console.log('pppp542545455453864')
        } else {
          const room = _.first(this.state.data)
          setNickName(room)
        }
      })
    }
  }

  handleInputChange(e, i) {
    const { rooms } = this.state
    rooms[i].nickname = e.target.value
    this.setState({ rooms })
  }

  onSaveClick() {
    const { setNickName } = this.props
    this.setState({ data: this.state.rooms }, () => {
      const room = _.first(this.state.data)
      setNickName(room)
    })
  }

  render() {
    const { rooms } = this.state
    return (
      <div>
        <main id="EditRoom">
          {rooms &&
            rooms.map((room, i) => {
              return (
                <div className="barcode-box" key={i} style={{ backgroundColor: this.getRandomColor(i) }}>
                  <div className="edit-room-name">
                    <input
                      type="text"
                      className="form-control"
                      style={{ color: '#ffffff' }}
                      name="cardNumber"
                      placeholder="Nickname"
                      value={_.get(room, 'nickname') || ''}
                      onChange={e => this.handleInputChange(e, i)}
                    />
                  </div>
                </div>
              )
            })}
        </main>
      </div>
    )
  }
}

What I am missing here? 我在这里想念的是什么?

Thank you !!! 谢谢 !!!

You should not modify this.state directly, eg using array mutating methods like splice . 不应该直接修改this.state ,例如,使用诸如splice类的数组变异方法。 Instead of this, make a copy from this.state.data sub-array, modify and pass it to setState() . 取而代之的是,从this.state.data子数组制作一个副本,修改并将其传递给setState()

Something like this: 像这样:

const data = this.state.data.slice() // make a copy of data
data.splice(0, 1) // modify a copy
this.setState({ data }, ...) // pass to setState

[ Update ] Explanation of why changing one sub-array of state affects on another: [ 更新 ]解释为什么更改一个状态子数组会影响另一状态:

Arrays (as all objects) in JS are passed by reference . JS中的数组(作为所有对象)通过reference传递。 So if you do a simple assignment like arr2 = arr1 , splice method will mutate the original array too. 因此,如果您进行简单的赋值,例如arr2 = arr1 ,则splice方法也会使原始数组发生变化。 That's also true for nested arrays (objects) like in your case. 对于像您这样的嵌套数组(对象)也是如此。 data sub-array is stored with rooms together in state . data子数组在staterooms一起存储。 So mutating data will affect rooms sub-array too. 因此,变异数据也会影响rooms子阵列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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