我正在使用React和Draftjs编写笔记编辑器。我现在遇到的问题是,即使组件已卸载,状态也不会改变,并且在下一个渲染中保持不变。
import React, {useState, useRef, useEffect} from 'react';
import {connect} from "react-redux";
import Proptype from "prop-types";
import Editor from 'draft-js-plugins-editor';
import {EditorState, ContentState} from "draft-js";
import CreateInlineToolbarPlugin from "draft-js-inline-toolbar-plugin";
import CustomInlineToolbar from "./CustomInlineToolbar";
import {updateTitle} from "../redux/action"
import "./NoteDetail.scss";
import 'draft-js-inline-toolbar-plugin/lib/plugin.css';
//TODOS: auto save function (need server)
const InlineToolbarPlugin = CreateInlineToolbarPlugin();
const {InlineToolbar} = InlineToolbarPlugin;
const NoteDetail = ({selectedNote, updateTitle}) => {
let {tags, note, _id, title} = selectedNote;
let [titleState, setTitleState] = useState(title);
let initContentState = ContentState.createFromText(note);
let [editorState, setEditorState] = useState(EditorState.createWithContent(initContentState));
let editorRef = useRef(React.createRef());
const onContentChange = (state) => {
setEditorState(state);
}
const focus = () => {
editorRef.current.focus()
}
const synTitle = (state) => {
updateTitle(state)
}
useEffect(()=>{
synTitle(_id, titleState)
}, [titleState, synTitle, _id])
useEffect(()=>{
console.log(titleState, title)
console.log(editorState.getCurrentContent().getPlainText())
},[title, editorState, titleState])
return(
<div>
<div className="NoteDetail-container">
<input type="text" id="title"
value={titleState === "Untitled Page"? "":titleState}
onChange={(e)=>setTitleState(e.target.value)}
/>
{/* <div id="tags">{renderTags(tags)}</div> */}
<div id="content" onClick={focus}>
<Editor
plugins={[InlineToolbarPlugin]}
onChange={onContentChange}
editorState={editorState}
ref={ele => editorRef.current = ele}
/>
<CustomInlineToolbar InlineToolbar={InlineToolbar} />
</div>
</div>
</div>
)
};
export default connect (null, {updateTitle})(NoteDetail)
我使用useEffect(第二个)检查道具是否正确传递。结果如下:
NoteDetail.js:44 Untitled Page1 (titleState) Untitled Page1 (title)
NoteDetail.js:44 Hi (editorState)
NoteDetail.js:43 Untitled Page1 (titleState) Untitled Page (title)
NoteDetail.js:44 Hi (editorState)
即使道具已更改,每个渲染的状态也相同。 有人可以帮忙吗?我会感激的