Draft.js 如何使用 redux store 正确更新 EditorState

How to use redux store to properly update EditorState in Draft.js

我在设置使用 EditorState.createEmtpy()EditorState.createWithContent() 的条件时遇到了一些困难。基本上,如果获取的数据包含保存的记录,我想显示该内容。如果没有,那我要EditorState.createEmtpy()

首先,这是我实际的 TextEditor 容器:

import React, { Component } from 'react';
import './styles/TextEditor.css';
import { Editor, EditorState, convertToRaw, convertFromRaw, ContentState} from 'draft-js';
import { connect } from 'react-redux';
import { addNewRecord, getRecord } from '../actions/recordActions.js';
import { bindActionCreators } from 'redux';

class TextEditor extends Component {
    constructor(props){
        super(props);
        this.state = {
            editorState: EditorState.createEmpty()
        }


            this.onChange = (editorState) => {
                const contentState = this.state.editorState.getCurrentContent();
                const editorStateJSONFormat = convertToRaw(contentState)
                this.props.addNewRecord(editorStateJSONFormat);
                this.setState({
                    editorState
                });
            }
        }


        componentDidMount = (props) => {
            this.props.getRecord()
        }

        componentWillReceiveProps = (nextProps, prevProps) => {
            let lastRecord;
            for (let i = nextProps.records.length; i > 0; i--){
                if (i === nextProps.records.length - 1){
                    lastRecord = nextProps.records[i].body
                }
            }
            const replaceRubyHashRocket = /=>/g
            const content = lastRecord.replace(replaceRubyHashRocket, ":")


            if (nextProps.records.length >= 1){
                this.setState({
                    editorState: EditorState.createWithContent(convertFromRaw(JSON.parse(content)))
                })
            } else{
                this.setState({
                    editorState: EditorState.createEmpty()
                })
            }
        }


    render(){
        return(
            <div id="document-container">
                <div >
                    <Editor 
                        editorState={this.state.editorState} 
                        onChange={this.onChange} 
                        placeholder="Type Below"
                        ref={this.setDomEditorRef}
                    />
                </div>
            </div>
        )
    }
}

const mapStateToProps = (state) => {
  return ({
    records: state.allRecords.records
  });
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({
    getRecord,
    addNewRecord
  }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(TextEditor)

一切正常,但我完全不知道应该使用哪种组件生命周期方法。

就目前而言,我可以在编辑器中键入内容,刷新,然后编辑器将显示正确的内容(数组中的最后一个元素)。问题是,当我在编辑器中添加更多内容时,我收到一条错误消息,指出 content 未定义。好像我的循环获取最后一个元素现在无效了?

对于上下文,这是我的减速器:

export default function manageDocuments(state = {loading: false,
}, action) {
    switch(action.type) {
        case 'PUSHING_RECORD':
            return {...state, loading: true}
        case "ADD_RECORD":
            return {...state, loading: false, records: action.payload}

        case "LOADING_RECORD":
            return {...state, loading: true}
        case "GET_RECORD":
            return {loading: false, ...state, records: action.payload}

        default:
            return {...state}
    }
};

这是我对 Rails API.POST/GET 请求的操作。

import fetch from 'isomorphic-fetch';

export function addNewRecord(editorStateJSONFormat) {
    const request = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8', "Accepts": "application/json"
        },
        body: JSON.stringify({body: editorStateJSONFormat})
    }

    return (dispatch) => {
        dispatch({type: 'PUSHING_RECORD'});
        return fetch('http://localhost:3001/api/v1/documents', request)
            .then(response => response.json())
            .then(records => {
                dispatch({type: 'ADD_RECORD', payload: records})
        });
    }
}

export function getRecord() {
    return (dispatch) => {
        dispatch({type: 'LOADING_RECORD'});

        return fetch('http://localhost:3001/api/v1/documents', {method: 'GET'})
            .then(response => response.json())
            .then(records => dispatch({type: 'GET_RECORD', payload: records}));
        }
}

我在这里结合了减速器(此时真的不需要):

import { combineReducers } from 'redux';
import docsReducer from './docsReducer';

    export default combineReducers({
      allRecords: docsReducer
    })

我在这里迷路了。我怎样才能做到这一点?

对于那些想知道的人,这似乎可以解决问题:

componentWillReceiveProps = (nextProps) => {
    if (nextProps.records.length >= 1){

        let lastRecord;
        for (let i = nextProps.records.length; i > 0; i--){
            if (i === nextProps.records.length - 1){
                lastRecord = nextProps.records[i].body
            }
        }

        const replaceRubyHashRocket = /=>/g
        const content = lastRecord.replace(replaceRubyHashRocket, ":")

        this.setState({
            editorState: EditorState.createWithContent(convertFromRaw(JSON.parse(content)))
        })
    }
}

将逻辑放在条件语句中,并删除:

this.setState({
     editorState: EditorState.createEmpty()
})

如果数据库为空,则允许创建一个空文档,或者如果数据库不为空,则始终return数组中的最后一个元素。

工作正常!

我知道 componentWillReceiveProps 已被弃用,但这是我完成所需任务的唯一方法。