【问题标题】:React slice() mutation convert with immer [closed]使用 immer 反应 slice() 突变转换 [关闭]
【发布时间】:2020-01-05 19:22:54
【问题描述】:

我在将这段代码转换为不变异时遇到问题。

我尝试过使用 immer,但我是新的 react 和 js

handleChange(nextField) {
    const { selectedIndex } = this.state
    const bookCopy = this.props.value.book.slice()

    bookCopy[selectedIndex].field_book_notes = nextField
    const nextValue = {
      ...this.props.value,
      books: bookCopy,
    }
    this.props.onChange(nextValue)
  }

有人建议我使用 immer 来解决突变问题。 我已经走了这么远,但不知道如何处理 nextValue = { ...this.props.value, 书籍:bookCopy,...... .等

handleChange(nextField) {
    const { selectedIndex } = this.state
    const bookCopy = product(this.props.value.book) => {

    bookCopy[selectedIndex].field_book_notes = nextField

.....

【问题讨论】:

  • 您是否遇到任何错误或错误?
  • 嗨,没有错误,但我还没有完成代码。我不知道如何使用 immer: const nextValue = { ...this.props.value, books: bookCopy, } 来满足这部分需求

标签: javascript reactjs mutation immer.js


【解决方案1】:

如果您不想改变初始数组 this.props.value.book,您应该改用 map

试试这个

handleChange(nextField) {
    const { selectedIndex } = this.state;
    const nextValue = {
      ...this.props.value,
      books: this.props.value.book.map((el, index) => {
        if (index !== selectedIndex) return el;
        return {
           ...el,
           field_book_notes: nextField
        }
      }),
    }
    this.props.onChange(nextValue)
  }

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2021-04-17
    • 2020-11-27
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 2019-07-20
    • 2010-12-30
    • 2014-06-08
    相关资源
    最近更新 更多