如何从setState中的数组中选择特定对象?

时间:2018-06-13 15:12:27

标签: javascript arrays reactjs

class Example extends React.Component{
    constructor(props){
        super(props);
        this.state = {
          array: [{n: 0}, {n: 1}, {n: 2}]
        }
    }
    
    selectObjectFromArray = index => {
      this.setState({
        array: //???
      })
    }

我们只知道索引,我们要编辑数组中的对象。我们不能像this.state.array[1] = ...那样做,我们不能setState({array[1]:...。我被认为是像array: [...this.state.array,这样的传播,但在这种情况下,我们无法设置,我们想要编辑的位置。那么在这种情况下我们能做些什么呢?

2 个答案:

答案 0 :(得分:1)

要更新状态数组,您必须创建它的副本,更新一些条目并将新数组推回状态。

以下是按钮更新最后一项的简单示例:

<div class="wrapper">
  <div class="block__one">
    <ul class="item">
      <li class="list">
        <div class="list__hover"></div>
      </li>
            <li class="list">
        <div class="list__hover"></div>
     
    </ul>
  </div>
  <div class="block__two"></div>
</div>

此工作示例也可在此处找到:https://codesandbox.io/s/o4x6mpnozq

答案 1 :(得分:1)

  

我们只知道索引,我们要编辑数组中的对象

给出knownIndex

this.setState({
  array:
    [ ...this.state.array.slice (0, knownIndex)  // <-- items up to the index
    , someUpdate(this.state.array[knownIndex]))  // <-- updated object
    , ...this.state.array.slice (knownIndex + 1) // <-- items after the index
    ]
})

另一种方法是使用Array .map函数。我们也让它成为通用函数

const updateAtIndex = (xs, i, f) =>
  xs .map ((x, j) => i === j ? f (x) : x)

在您的组件中,您可以像这样使用它

this.setState ({
  array: updateAtIndex (this.state.array, knownIndex, f)
})

其中f是更新对象的函数,例如

// returns a new object with the n property doubled
const f = obj =>
  ({ n: obj.n * 2 })

编写泛型函数时,我喜欢让它们更健壮。如果您在程序中使用此技术,我建议对上述函数进行一些更改。这些更改更有效地传递参数类型,并允许读者更好地推断函数返回类型。

const identity = x =>
  x

const updateAtIndex = (xs = [], i = 0, f = identity) =>
  xs .map ((x, j) => i === j ? f (x) : x)

const f = ({ n = 0 }) =>
  ({ n: n * 2 })