在重新渲染期间,React prop 值未在对象初始化中更新

问题描述

我有一个在渲染期间创建配置对象的组件。配置对象依赖于作为 prop 传入的值。当道具更改时,我希望配置对象内部的值更新。下面是组件的样子:

export const LeaseEditor = ({ onChange,leaseDocument,save,rentTableData }: any) => {
  // rentTableData is the prop that will change
  console.log(rentTableData) // this shows the correct values when the prop changes

  const config = {
    ...
    rentTable: {
      rentTableRenderer: (domElement: any) => {
        console.log('rentTableData in method',rentTableData) // when the prop changes,this value is not updated,it logs the prevIoUs value when this is invoked
        ReactDOM.render(<RentTablePreview values={rentTableData} />,domElement)
      },},}

  return (
    <div className="lease-editor">
      <div className="lease-editor__toolbar" ref={toolbarElem}></div>

      <div className="lease-editor__editable-container">
        {leaseDocument.body && rentTableData && (
          <CKEditor
            editor={Editor}
            isReadOnly={false}
            config={config} // config object Feeds in fine during the first render
            data={leaseDocument.body}
          />
        )}
      </div>
    </div>
  )
}

rentTableData 更新时,该值会正确记录在组件中,但是当从配置中调用方法时,它使用先前的值(在第一次渲染时 prop 是什么)。

关于如何解决这个问题有什么想法吗?

解决方法

我对 CKEditor 没有任何经验,但它可能没有考虑对 config 道具的更改,这可以解释过时的值。您可以使用 useRef (docs) 获取 rentTableRenderer 以使用 rentTableData 的当前值。

只需添加一个新常量 rentTableDataRef 并将箭头函数主体中的 rentTableData 替换为 rentTableData.current

export const LeaseEditor = ({ onChange,leaseDocument,save,rentTableData }: any) => {
  // rentTableData is the prop that will change
  console.log(rentTableData) // this shows the correct values when the prop changes
  const rentTableDataRef = useRef(rentTableData)

  const config = {
    ...
    rentTable: {
      rentTableRenderer: (domElement: any) => {
        console.log('rentTableData in method',rentTableDataRef.current)
        ReactDOM.render(<RentTablePreview values={rentTableDataRef.current} />,domElement)
      },},}