我有一个存储在redux状态存储中的map和一个react组件,它呈现我存储在map中的值。现在,当我在这个map中添加/删除值时,我的react组件不会使用最新的更改进行自我更新。
注意:我看到我们可以使用mobX
模块来监听映射(或数组以外的其他数据结构)中的更改,但我不想使用其他模块来实现这一点。
我的Redux商店
const initialState = {
myNotes = new Map();
}
我的Reducer
case CREATE_NEW_NOTE:
const { noteAdded, success } = action.payload;
let newOwnerNotes = state.myNotes;
newOwnerNotes.set(noteAdded.note_id, noteAdded);
if (success) {
return {
...state,
myNotes: newOwnerNotes
};
} else {
return {
...state
};
}
case DELETE_NOTE:
const noteIdToDelete = action.payload.note_id;
const { success } = action.payload;
let newState = Object.assign({}, state);
if (success) {
newState.myNotes.delete(noteIdToDelete);
return {
...newState
};
} else {
return {
...state
};
}
我的React组件
import React from "react";
import { connect } from "react-redux";
// Components
import Notes from "../notes/Notes";
import Heading from "./Heading";
class Owner extends React.Component {
render() {
const { myNotes } = this.props;
debugger;
return (
<div className="notes-owner">
<div className="notes-owner-header">
<Heading owner={true} />
</div>
<div className="notes-owner-content">
{[...myNotes].map(([key, note]) => {
return (
<Notes note={note} owner={true} key={note.note_id}>
{note.title}
</Notes>
);
})}
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
myNotes: state.notes.myNotes
};
};
export default connect(
mapStateToProps,
{}
)(Owner);
发布于 2019-05-25 03:29:42
您不应该使用Map
,至少不应该这样使用。你正在改变状态。看这一行:
let newOwnerNotes = state.myNotes;
newOwnerNotes.set(noteAdded.note_id, noteAdded);
您只是引用了同一个对象。试着这样做:
let newOwnerNotes = new Map(state.myNotes);
newOwnerNotes.set(noteAdded.note_id, noteAdded);
您应该始终记住,数组、对象、映射都是reference types
,请看以下代码片段:
const arr = [1,2,3,4,5]
const copy = arr
const realCopy = [...arr]
console.log(copy, realCopy) //[1,2,3,4,5],[1,2,3,4,5]
console.log(copy === arr) //true
console.log(realCopy === arr) //false
当您只是指定like const copy = arr
时,您不是在创建另一个数组,而是在引用相同的对象,但是在第二种情况下(使用扩展操作符),您将创建另一个包含来自arr
的所有项的扩展的数组。有关immutability in JS的更多信息,请单击此处。
当您执行const newNotes = new Map(state.myNotes)
时,您正在创建另一个对象,现在您进行了修改,最后:return {...state, myNotes: newOwnerNotes};
https://stackoverflow.com/questions/56298522
复制相似问题