[英]How to use redux store to properly update EditorState in Draft.js
I am having a bit of difficulty setting a conditional that utilizes EditorState.createEmtpy()
or EditorState.createWithContent()
. 我在设置使用
EditorState.createEmtpy()
或EditorState.createWithContent()
的条件时遇到了一些困难。 Basically, if the fetched data contains a saved record, I want to display that content. 基本上,如果获取的数据包含已保存的记录,我想显示该内容。 If not, then I want
EditorState.createEmtpy()
如果没有,那么我想要
EditorState.createEmtpy()
To start, here is my actual TextEditor container: 首先,这是我实际的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)
Everything is working fine but I am completely lost as to what component lifecycle method I should be using. 一切工作正常,但是我完全迷失了应该使用的组件生命周期方法。
As it stands, I can type something into the editor, refresh, and then the editor will display the correct content (the last element in the array). 就目前而言,我可以在编辑器中键入内容,刷新,然后编辑器将显示正确的内容(数组中的最后一个元素)。 The problem is, when I go to add more content in the editor, I get an error that says
content
is undefined. 问题是,当我在编辑器中添加更多内容时,出现错误消息,
content
未定义。 It's like my loop getting the last element is now void? 就像我获取最后一个元素的循环现在无效了吗?
For context, here is my reducer: 对于上下文,这是我的减速器:
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}
}
};
Here is my action for POST/GET request from my Rails API. 这是我对来自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}));
}
}
I combined reducers here (don't really need to at this point): 我在这里组合了减速器(此时实际上并不需要):
import { combineReducers } from 'redux';
import docsReducer from './docsReducer';
export default combineReducers({
allRecords: docsReducer
})
I am pretty lost here. 我在这里很迷路。 How could I achieve this?
我怎样才能做到这一点?
For those wondering, this seemed to do the trick: 对于那些想知道的人,这似乎可以解决问题:
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)))
})
}
}
Putting the logic inside the conditional, and removing: 将逻辑放入条件中,然后删除:
this.setState({
editorState: EditorState.createEmpty()
})
allowed an empty document to be created if the DB is empty, or always return the last element in the array if the DB is not empty. 如果数据库为空,则允许创建一个空文档;如果数据库不为空,则总是返回数组中的最后一个元素。
Works fine! 工作正常!
I know componentWillReceiveProps
is deprecated but it was the only way I could accomplish what I needed to. 我知道
componentWillReceiveProps
已过时,但这是我可以完成所需工作的唯一方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.