Как корректно подгрузить props в app react-redux компоненте
Всем здрасьте. У меня приложение react-redux. Мне нужно подгрузить динамически обновляемые пропсы в один из компонентов (./popups/EditNotePopup.js) с своим стейтом. Так вот сейчас нужные пропсы подгружаются только при повторном вызове(при повторном нажатии кнопки editNote). Я подозреваю, что некорректно использую componentWillReceiveProps(). Подскажите, как сделать правильно и почему?
import React, { Component } from "react"; import $ from "jquery"; import { serialiseEditorStateToRaw } from "draftjs-conductor"; import { EditorState, ContentState, convertFromHTML, convertFromRaw } from "draft-js"; import { convertToHTML } from "draft-convert"; import { DraftailEditor, BLOCK_TYPE, INLINE_STYLE } from "draftail"; import { exporterConfig, CustomIcon, BR_ICON, UNDO_ICON, REDO_ICON } from "../components"; import "draft-js/dist/Draft.css"; import "draftail/dist/draftail.css"; //для справки, если потребуется [url]https://www.draftail.org/docs/controlled-component[/url] [url]https://draftjs.org/docs/api-reference-content-state[/url] export class EditNotePopup extends Component { getContent = stringHTML => { const blocksFromHTML = convertFromHTML(stringHTML); const content = ContentState.createFromBlockArray( blocksFromHTML.contentBlocks ); return content; }; state = { editorState: EditorState.createEmpty() }; onChange = editorState => this.setState({ editorState: editorState }); clearEditor = () => { this.setState({ editorState: EditorState.createEmpty() }); }; componentWillReceiveProps() { if (this.props.textEditedNote !== "") { this.setState({ editorState: EditorState.createWithContent( this.getContent(this.props.textEditedNote) ) }); } } // for export text note toHTML toHTML = raw => raw ? convertToHTML(exporterConfig)(convertFromRaw(raw)) : ""; render() { return ( <div id="modal-editNote" className="modal fade" tabIndex={-1} role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" > <div className="modal-dialog modal-dialog-centered" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title">EditNote</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">×</span> </button> </div> <form id="formEditNote" onSubmit={ev => ev.preventDefault()} className="needs-validation" noValidate > <div className="modal-body"> <div className="form-label-group"> <label htmlFor="editTextNote">Text Note</label> <DraftailEditor editorState={this.state.editorState} onChange={this.onChange} }} /> </div> </div> <div className="modal-footer"> <button onClick={() => { $("#modal-editNote").modal("hide"); const idNote = this.props.idNote; const editedTextNote = this.toHTML( serialiseEditorStateToRaw(this.state.editorState) ); this.props.editNote(idNote, editedTextNote); this.clearEditor(); }} type="button" className="btn btn-success btn-block mt-3" > SAVE </button> </div> </form> </div> </div> </div> ); } } link full project https://codesandbox.io/s/noteeditors-co2pe |
Вобщем, кому интересно, ответ нашёлся здесь
https://stackoverflow.com/questions/...for-react-hook Пришлось реализовать на hooks export const EditNotePopup = (props) => { const { editNote, idNote, textEditedNote } = props const [editorState, setEditorState] = useState(EditorState.createEmpty()) const getContentFromHTML = (stringHTML) => { const blocksFromHTML = convertFromHTML(stringHTML); const content = ContentState.createFromBlockArray( blocksFromHTML.contentBlocks ); return content } useEffect (() => { if(textEditedNote !==""){ setEditorState( EditorState.createWithContent( getContentFromHTML(textEditedNote) ) ); } }, [textEditedNote]); // for export text note toHTML const toHTML = (raw) => raw ? convertToHTML(exporterConfig)(convertFromRaw(raw)) : "" return ( <div id="modal-editNote" className="modal fade" tabIndex={-1} role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" > <div className="modal-dialog modal-dialog-centered" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title">EditNote</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">×</span> </button> </div> <form id="formEditNote" onSubmit={ev => ev.preventDefault()} className="needs-validation" noValidate > <div className="modal-body"> <div className="form-label-group"> <label htmlFor="editTextNote">Text Note</label> <DraftailEditor editorState={editorState} onChange={setEditorState} /> </div> </div> <div className="modal-footer"> <button onClick={() => { $("#modal-editNote").modal("hide") // приводим текст записи к html-string const editedTextNote = toHTML( serialiseEditorStateToRaw( editorState ) ) // отправляем editedNote в store editNote(idNote, editedTextNote); // очищаем поле редактора setEditorState(EditorState.createEmpty()); }} type="button" className="btn btn-success btn-block mt-3" > SAVE </button> </div> </form> </div> </div> </div> ) } Тему можно закрывать |
На будущее
UNSAFE_componentWillReceiveProps(nextProps) { //nextProps - это данные которые пришли } |
Часовой пояс GMT +3, время: 16:50. |