我使用react-quill制作了一个富文本编辑器。我想用this.state存储数据,这样可以自动保存输入文本框的内容,刷新页面后文本输入不会消失。
代码是针对react-quill的,如何修改代码来实现我的目标?
import React from 'react'
export default class Editor extends React.Component {
constructor (props) {
super(props)
this.state = {
editorHtml: '',
}
this.handleChange = this.handleChange.bind(this)
if (typeof window !== 'undefined') {
this.ReactQuill = require('react-quill')
}
}
handleChange (html) {
this.setState({ editorHtml: html });
}
render() {
const ReactQuill = this.ReactQuill
if (typeof window !== 'undefined' && ReactQuill) {
return (
<div className='app'>
<ReactQuill
onChange={this.handleChange}
value={this.state.editorHtml}
modules={Editor.modules}
formats={Editor.formats}
/>
)
} else {
return null;
}
}
}
Editor.modules = {
toolbar: [
[{ 'header': '1'}, {'header': '2'}, { 'font': [] }],
[{size: []}],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[{'list': 'ordered'}, {'list': 'bullet'},
{'indent': '-1'}, {'indent': '+1'}],
['link', 'image', 'video'],
['clean']
],
clipboard: {
matchVisual: false,
}
}
Editor.formats = [
'header', 'font', 'size',
'bold', 'italic', 'underline', 'strike', 'blockquote',
'list', 'bullet', 'indent',
'link', 'image', 'video'
]发布于 2019-08-06 17:04:13
您的数据应该保存在哪里?
您没有提到后端服务,所以我不确定您想要将此数据保存在哪里。由于react在每次页面刷新时都会重新运行,因此您不能存储数据,只能从api或本地存储中检索数据。
本地存储
如果你想将数据存储在本地存储中,你需要在你的应用程序加载时使用hydrate。这是查找本地存储并检索数据以供使用的过程。请注意,这些数据只能从编写它的机器和浏览器访问,如果您想将其发布到其他平台上,这是不好的。
API接口
如果您希望将数据存储在“云”中以供以后检索,则应该创建一个api来处理post和get请求。这些将允许您将数据保存到已连接的云数据库中。在这种情况下,当调用componentDidMount时,您可以使用get请求检索以前的会话数据。
Lambda函数
与api类似,您可以编写“无服务器”函数来处理数据。firebase函数是一个很好的起点,它们很容易理解并在几分钟内编写。
结论
所有这些解决方案都需要相当长的时间才能组合起来,除了使用第三方服务或设置自己的服务器和数据库之外,没有什么“简单”的方法来存储和检索数据。
发布于 2019-08-06 17:11:07
你想在哪里存储数据是主要的问题。如果您要将其保存到数据库并具有用于获取数据的终结点。我们说"http://localhost:3001/api/form/data“吧。
向端点发出请求,在React的componentDidMount方法中获取数据后设置状态,如下所示:
componentDidMount(){
fetch("http://localhost:3001/api/form/data")
.then(res=>res.json())
.then(data=>{
if(data){
this.setState.({editorHtml : data});
}
}).catch(ex){
//handle error here
}https://stackoverflow.com/questions/57372284
复制相似问题