【发布时间】:2016-10-13 07:19:38
【问题描述】:
我正在尝试从数据库中读取数据,然后通过 react 渲染到 DOM。对于输入,我使用了 draft.js 并在保存到数据库之前对其运行 convertToRaw。但是,当我运行 convertFromRaw 并渲染时,我在控制台中收到此错误:“未捕获的类型错误:无法读取未定义的属性‘块’”。这是我第一次使用 draft.js,所以我不确定我做错了什么。有人可以帮忙吗?太感谢了!
//App.js
import React, {
Component
}
from 'react';
import Blogs from './blogs';
import {
Editor, EditorState, convertToRaw
}
from 'draft-js'
// include horizon client
const Horizon = require('@horizon/client');
const horizon = Horizon({
secure: false
});
// init blogs collection in rethinkdb
const blogger = horizon('blogs')
class App extends Component {
constructor(props) {
super(props);
this.state = {
title: false,
author: false,
editorState: EditorState.createEmpty()
}
}
// watch form values for change
handleChangeTitle(event) {
this.setState({
title: event.target.value
});
}
handleChangeAuthor(event) {
this.setState({
author: event.target.value
});
}
handleChangeBody(editorState) {
this.setState({
editorState
});
}
writeBlog() {
// check for empty string and return error to user
if (this.state.title === false || this.state.author === false || this.state.body === false) {
alert('Invalid Submission: One or more fields are empty');
return;
}
let blog = {
title: this.state.title,
author: this.state.author,
editorState: convertToRaw(this.state.editorState.getCurrentContent())
};
// store the inputs in the database
blogger.store(blog);
}
render() {
return ( < form >
< div className = "center" >
< Blogs blogger = {
blogger
}
/>
<div className="writer">
<div className="basic-inputs">
<div className="input-unit">
<label>Title</label >
< input onChange = {
this.handleChangeTitle.bind(this)
} > < /input>
</div >
< div className = "input-unit" >
< label > Author < /label>
<input onChange={this.handleChangeAuthor.bind(this)}></input >
< /div>
</div >
< label > Blog < /label>
<Editor onChange={this.handleChangeBody.bind(this)} editorState={this.state.editorState} / >
< button onClick = {
this.writeBlog.bind(this)
} > Post < /button>
</div >
< /div>
</form >
);
}
}
export
default App;
import React, { Component } from 'react';
import {convertFromRaw} from 'draft-js'
export default class Blog extends Component {
constructor(props) {
super(props)
this.props = props;
}
render() {
return (
<div className="blog-container">
<h2 className="title">{this.props.blg.title}</h2>
<h4 className="author">{this.props.blg.author}</h4>
<p className="body">{convertFromRaw(this.props.blg.body)}</p>
</div>
);
}
}
【问题讨论】:
-
this.props.blg.body返回什么? -
它将draftjs输入的状态作为来自数据库的对象返回
-
如果你这样做会发生什么
convertFromRaw(JSON.parse(this.props.blg.body)) -
嗯,我在控制台中遇到错误; “未捕获的 SyntaxError:JSON 中位置 0 处的意外标记 u”
标签: javascript reactjs rethinkdb draftjs