【发布时间】:2019-10-03 02:31:47
【问题描述】:
我有一个编辑器的 Immutable.js 记录,其中包含内容和选择的嵌套记录。
So whenever the selection changes, I would get the start and end points of the selection, and then update the state with a new selection.
class SelectionStateRecord extends Immutable.Record({
anchor: 0,
focus: 0,
}
) {
// extra features
}
class EditorRecord extends Immutable.Record({
key: uuid.v4(),
ContentState: new ContentStateRecord(),
SelectionState: new SelectionStateRecord(),
}
) {
// extra features
}
export default class TextEditor extends React.Component {
constructor(props) {
super(props)
this.state = {
EditorState: new EditorRecord()
...
}
}
_onSelectionChange = e => {
const {start, end} = e.nativeEvent.selection
const newEditorState = this.state.EditorState.SelectionState.merge({
focus: start,
anchor: end,
})
this.setState({EditorState: newEditorState})
}
render() {
...
}
}
但是,我收到了这个错误,我猜我不能只为嵌套记录设置一个新值:
undefined 不是对象(评估 '_this.state.EditorState.SelectionState.merge')
但是,这是可行的:
_onSelectionChange = e => {
const {start, end} = e.nativeEvent.selection
const newEditorState = this.state.EditorState.merge({
key: uuid.v4(),
ContentState: this.state.EditorState.ContentState,
SelectionState: this.state.EditorState.SelectionState.merge({
focus: start,
anchor: end,
}),
})
this.setState({EditorState: newEditorState}, () => {
console.log('start', this.state.EditorState.SelectionState.start())
})
}
我只是不确定这是否是更新状态的正确方法,并且对如何设置/更新单个嵌套不可变记录的值以避免性能损失感到困惑。
【问题讨论】:
标签: reactjs immutable.js