首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用redux存储正确更新Draft.js中的Draft.js

如何使用redux存储正确更新Draft.js中的Draft.js
EN

Stack Overflow用户
提问于 2018-11-29 00:30:38
回答 1查看 1.8K关注 0票数 2

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

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

代码语言:javascript
复制
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是未定义的。就像我的循环得到的最后一个元素现在是无效的?

就上下文而言,这是我的还原剂:

代码语言:javascript
复制
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请求的操作。

代码语言:javascript
复制
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}));
        }
}

我在这里组合了减速机(现在不需要这么做):

代码语言:javascript
复制
import { combineReducers } from 'redux';
import docsReducer from './docsReducer';

    export default combineReducers({
      allRecords: docsReducer
    })

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-29 16:34:47

对于那些想知道的人来说,这似乎起了作用:

代码语言:javascript
复制
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)))
        })
    }
}

将逻辑放入条件中,并删除:

代码语言:javascript
复制
this.setState({
     editorState: EditorState.createEmpty()
})

允许在DB为空的情况下创建空文档,或者如果DB不是空的,则始终返回数组中的最后一个元素。

工作得很好!

我知道componentWillReceiveProps是不受欢迎的,但这是我唯一能完成我需要的事情的方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53530138

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档