反应slice()突变与沉浸转换

时间:2019-09-02 20:19:23

标签: javascript reactjs mutation immer.js

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

我尝试使用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)
  }

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

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

    bookCopy[selectedIndex].field_book_notes = nextField

.....

1 个答案:

答案 0 :(得分: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)
  }