Javascript 使用immer进行React slice()转换
我在将这段代码转换为不变异时遇到问题 我尝试过使用immer,但我是新的react和jsJavascript 使用immer进行React slice()转换,javascript,reactjs,mutation,immer.js,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 = {
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={
…这个。道具。价值,
书籍:书籍副本等
handleChange(nextField) {
const { selectedIndex } = this.state
const bookCopy = product(this.props.value.book) => {
bookCopy[selectedIndex].field_book_notes = nextField
如果你不想改变初始数组
这个.props.value.book
你应该使用映射
试试这个
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)
}
您是否有任何错误或bug?您好,没有错误,但我还没有完成代码。我不知道如何使用immer:const nextValue={…this.props.value,books:bookCopy,}