Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs draft.js-从db检索格式化文本_Reactjs_Cors_Text Editor_Draftjs - Fatal编程技术网

Reactjs draft.js-从db检索格式化文本

Reactjs draft.js-从db检索格式化文本,reactjs,cors,text-editor,draftjs,Reactjs,Cors,Text Editor,Draftjs,My draft.js用文本填充正文,例如:'{“blocks”:[{“key”:“3mont”,“text”:“lorem ipsum”,“type”:“unstyled”,“depth”:0,“inlineStyleRanges”:[],“entityRanges”:[],“data”:{}}],“entityMap”:{}}'并在使用Convertoraw()后将其保存到数据库中 在Post.js中,我想从数据库中检索并显示格式化的文本。 我已经读到,为了做到这一点,我必须使用conver

My draft.js
用文本填充
正文
,例如:
'{“blocks”:[{“key”:“3mont”,“text”:“lorem ipsum”,“type”:“unstyled”,“depth”:0,“inlineStyleRanges”:[],“entityRanges”:[],“data”:{}}],“entityMap”:{}}'
并在使用
Convertoraw()后将其保存到数据库中

Post.js
中,我想从数据库中检索并显示格式化的
文本。
我已经读到,为了做到这一点,我必须使用
convertToRaw()
,然后在从数据库检索它时使用
convertFromRaw()
,但我遇到的问题与每当我使用
convertFromRaw()时(我收到
cors
错误和
位置0处JSON中意外的标记u)相同
并尝试从数据库中检索格式化的
文本

我已经将服务器设置为支持
cors
那么为什么我会收到
cors
错误?是因为我试图将无效响应解析为
JSON
? 如何从
Post.js
中的数据库获取格式化的
文本?
任何帮助都将不胜感激

CreatePost.js

class CreatePost extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "",
      body: EditorState.createEmpty(),
    };
  }

  changeHandler = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  submitHandler = (e) => {
    e.preventDefault();
    const {
      user: { _id },
    } = isAuthenticated();
    axios({
      url: `${API}/post/new-post/${_id}`,
      method: "POST",
      data: {
        ...this.state,
        body: JSON.stringify(convertToRaw(this.state.body.getCurrentContent())),
      },
    })
      .then((response) => {
      //  this.setState({ createdPost: this.state.title });
       return response
      })
      .catch((error) => {
        if (!this.state.title || !this.state.body) {
          this.setState({
            error: "This post must contain a title and a body.",
          });
        }
        console.log(error);
      });
  };

   // Attempt to map through blocks
   //getText = () => {
   // const {body} = this.state;
   //const arr = body.blocks.map(({ text }) => text).join(' ')
   // console.log(arr)
  //}

  render() {
    const { title, body } = this.state;

    return (
      <>
        <Navbar />
        <Tabs>
          <TabList>
            <Tab>Draft</Tab>
            <Tab>Preview</Tab>
          </TabList>
          <TabPanel>
            <div>
              <form onSubmit={this.submitHandler}>
                <div>
                // title input
                </div>
                <div>
                  <TextEditor
                    onChange={(value) => this.setState({ body: value })}
                    editorState={body}
                  />
                </div>
                <button type="submit">
                  Publish
                </button>
              </form>
            </div>
          </TabPanel>

          <TabPanel>
            <div>
              <h1>{title}</h1>
                // display body text value here too 
              {this.getText()}
            </div>
          </TabPanel>
        </Tabs>
      </>
    );
  }
}
TextEditor.js

class TextEditor extends React.Component {
  constructor(props) {
    super(props);
    this.plugins = [addLinkPlugin];
  }
  toggleBlockType = (blockType) => {
    this.props.onChange(RichUtils.toggleBlockType(this.props.editorState, blockType));
  };
  handleKeyCommand = (command) => {
    const newState = RichUtils.handleKeyCommand(
      this.props.editorState,
      command
    );
    if (newState) {
      this.props.onChange(newState);
      return "handled";
    }
    return "not-handled";
  };

  onUnderlineClick = () => {
    this.props.onChange(
      RichUtils.toggleInlineStyle(this.props.editorState, "UNDERLINE")
    );
  };

  onBoldClick = (event) => {
    this.props.onChange(RichUtils.toggleInlineStyle(this.props.editorState, "BOLD"));
  };

  onItalicClick = () => {
    this.props.onChange(
      RichUtils.toggleInlineStyle(this.props.editorState, "ITALIC")
    );
  };

  onAddLink = () => {
    const editorState = this.props.editorState;
    const selection = editorState.getSelection();
    const link = window.prompt("Paste the link -");
    if (!link) {
      this.props.onChange(RichUtils.toggleLink(editorState, selection, null));
      return "handled";
    }
    const content = editorState.getCurrentContent();
    const contentWithEntity = content.createEntity("LINK", "MUTABLE", {
      url: link,
    });
    const newEditorState = EditorState.push(
      editorState,
      contentWithEntity,
      "create-entity"
    );
    const entityKey = contentWithEntity.getLastCreatedEntityKey();
    this.props.onChange(RichUtils.toggleLink(newEditorState, selection, entityKey));
  };

  toggleBlockType = (blockType) => {
    this.props.onChange(RichUtils.toggleBlockType(this.props.editorState, blockType));
  };

  render() {
    return (
      <div>
      // formatting buttons
        <div>
          <Editor
          blockStyleFn={getBlockStyle}
          editorState={this.props.editorState}
          handleKeyCommand={this.handleKeyCommand}
          onChange={this.props.onChange}
          plugins={this.plugins}
          placeholder="Post Content"
          />
        </div>
      </div>
    );
  }
}
类文本编辑器扩展了React.Component{
建造师(道具){
超级(道具);
this.plugins=[addLinkPlugin];
}
toggleBlockType=(blockType)=>{
this.props.onChange(RichUtils.toggleBlockType(this.props.editorState,blockType));
};
handleKeyCommand=(命令)=>{
const newState=RichUtils.handleKeyCommand(
这个.props.editorState,
命令
);
如果(新闻状态){
this.props.onChange(newState);
返回“已处理”;
}
返回“未处理”;
};
onUnderlineClick=()=>{
这个。道具。改变(
RichUtils.toggleInlineStyle(this.props.editorState,“下划线”)
);
};
onBoldClick=(事件)=>{
this.props.onChange(RichUtils.toggleInlineStyle(this.props.editorState,“粗体”);
};
单击鼠标右键=()=>{
这个。道具。改变(
RichUtils.toggleInlineStyle(this.props.editorState,“斜体”)
);
};
onAddLink=()=>{
const editorState=this.props.editorState;
const selection=editorState.getSelection();
const link=window.prompt(“粘贴链接-”);
如果(!链接){
this.props.onChange(RichUtils.toggleLink(editorState,selection,null));
返回“已处理”;
}
const content=editorState.getCurrentContent();
const contentWithEntity=content.createEntity(“链接”,“可变”{
网址:link,
});
const newEditorState=EditorState.push(
编辑状态,
满足于实体,
“创建实体”
);
const entityKey=contentWithEntity.getLastCreatedEntityKey();
this.props.onChange(RichUtils.toggleLink(newEditorState,selection,entityKey));
};
toggleBlockType=(blockType)=>{
this.props.onChange(RichUtils.toggleBlockType(this.props.editorState,blockType));
};
render(){
返回(
//格式化按钮
);
}
}

显然
草稿js
没有html输出功能,因为它应该对输出没有任何假设,所以人们可以根据自己的需要调整输出()。这意味着我们必须自己实现它,如果您只想在数据库中保存一个html或降价输出,那么mono repo可能会有所帮助。我已经实现了一个如何在中实现它的示例。请注意,我使用了
危险的LysetinerHTML
进行演示,这不是最佳的。您可能希望使用净化和富文本组件来显示帖子。事实上,如果可能的话,我建议放弃html,改为降价。

谢谢你的回答!它现在显示(格式化)在CreatePost.js的另一个选项卡上。不过,我仍在努力让它显示在Post.js中。当我将
onPublish
方法添加到CreatePost.js中的按钮时,我得到的
this.props.onPublish不是一个函数
,当我取出它并保持按钮不变时,我得到的输出与之前相同@Jackson@Rahni我的沙盒已经有
Post.js
onPublish
。当您单击发布按钮时,它只会显示
Post.js
的实例。我想你没有在我的沙盒中点击发布按钮?
class TextEditor extends React.Component {
  constructor(props) {
    super(props);
    this.plugins = [addLinkPlugin];
  }
  toggleBlockType = (blockType) => {
    this.props.onChange(RichUtils.toggleBlockType(this.props.editorState, blockType));
  };
  handleKeyCommand = (command) => {
    const newState = RichUtils.handleKeyCommand(
      this.props.editorState,
      command
    );
    if (newState) {
      this.props.onChange(newState);
      return "handled";
    }
    return "not-handled";
  };

  onUnderlineClick = () => {
    this.props.onChange(
      RichUtils.toggleInlineStyle(this.props.editorState, "UNDERLINE")
    );
  };

  onBoldClick = (event) => {
    this.props.onChange(RichUtils.toggleInlineStyle(this.props.editorState, "BOLD"));
  };

  onItalicClick = () => {
    this.props.onChange(
      RichUtils.toggleInlineStyle(this.props.editorState, "ITALIC")
    );
  };

  onAddLink = () => {
    const editorState = this.props.editorState;
    const selection = editorState.getSelection();
    const link = window.prompt("Paste the link -");
    if (!link) {
      this.props.onChange(RichUtils.toggleLink(editorState, selection, null));
      return "handled";
    }
    const content = editorState.getCurrentContent();
    const contentWithEntity = content.createEntity("LINK", "MUTABLE", {
      url: link,
    });
    const newEditorState = EditorState.push(
      editorState,
      contentWithEntity,
      "create-entity"
    );
    const entityKey = contentWithEntity.getLastCreatedEntityKey();
    this.props.onChange(RichUtils.toggleLink(newEditorState, selection, entityKey));
  };

  toggleBlockType = (blockType) => {
    this.props.onChange(RichUtils.toggleBlockType(this.props.editorState, blockType));
  };

  render() {
    return (
      <div>
      // formatting buttons
        <div>
          <Editor
          blockStyleFn={getBlockStyle}
          editorState={this.props.editorState}
          handleKeyCommand={this.handleKeyCommand}
          onChange={this.props.onChange}
          plugins={this.plugins}
          placeholder="Post Content"
          />
        </div>
      </div>
    );
  }
}