即使更改道具后也不调用ReactJS componentDidUpdate

时间:2020-07-27 15:44:44

标签: javascript reactjs functional-programming draftjs

我正在使用draft-js进行响应,在这里我进行了api调用(在FUNCTIONAL PARENT COMPONENT中)并获取要在编辑器中放置的内容。我收到了以下代码,可以在道具中接收到的数据插入到编辑器中:

父项:

var draftContent = "";
var isContentFetched = false;

const CommentSection = () => {
      let response = await fetch(url, {
        method: "get",
        headers: headers,
      });

      let query = await response.json(); // read response body and parse as JSON
      draftContent = element.comment;
      isContentFetched = true;
      return(<RichTextEditor
                isDraftFetched={isDraftFetched}
                isContentFetched={isContentFetched}
                placeholder=""
                rows={6}
                boxWidth="100%"
                boxHeight="155px"
              />)
})

编辑器组件:

  componentDidUpdate(props) {
      if(this.props.isContentFetched == true && draftAlreadyFilled== false) {
        this._insertText(this.props.draftContent);
        draftAlreadyFilled = true;
      }
  }

 _insertText(htmlContent) {
    this.setState({
      editorState: EditorState.createWithContent(
        ContentState.createFromBlockArray(
          convertFromHTML(htmlContent)
        )
      ),
    })
  }

问题是,通过道具加载和发送的文本未在编辑器中填写。相反,一旦我进入页面并单击“刷新”,它就会很好地加载。

PS:1.我检查了相关问题,但这些解决方案无效。 2.确实有必要在父组件中进行API调用。

1 个答案:

答案 0 :(得分:0)

从外部api获取数据是一种副作用,请改用useEffect Hook。使用传递给useEffect方法的函数在内部进行ajax调用。