【问题标题】:Updating the state with nested Immutable records使用嵌套的不可变记录更新状态
【发布时间】: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


    【解决方案1】:

    你能用updateIn()吗? docs

    例如

    _onSelectionChange = e => {
            const {start, end} = e.nativeEvent.selection
            const newEditorState = this.state
              .updateIn(
                ['EditorState', 'SelectionState'],
                new SelectionStateRecord(), // default value (optional)
                ss => ss.set('focus', start).set('anchor', end)
              )
            )
    
            this.setState({EditorState: newEditorState}, () => {
                console.log('start', this.state.EditorState.SelectionState.start())
            })
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 2016-11-10
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      相关资源
      最近更新 更多