【问题标题】:React prop value not updating in object initialization during re renderReact prop 值在重新渲染期间未在对象初始化中更新
【发布时间】:2021-05-09 04:04:10
【问题描述】:

我有一个在渲染期间创建配置对象的组件。配置对象依赖于作为 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 更新时,该值会正确记录在组件中,但是当从配置中调用该方法时,它会使用之前的值(第一次渲染时的道具)。

关于如何解决此问题的任何想法?

【问题讨论】:

    标签: reactjs ckeditor ckeditor5


    【解决方案1】:

    我对 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)
          },
        },
      }
    

    【讨论】:

    • 对 ref 不太熟悉,但您提供的代码 rentTableDataRef.current 对我来说是空的。是不是因为第一次渲染时 prop 的值为 null?
    • 在此之后,我使用 useEffect 在道具更改时手动更新 ref 并解决了我的问题。非常感谢,已经挣扎了几个小时!
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2021-12-15
    • 2016-12-30
    • 2022-11-22
    • 1970-01-01
    相关资源
    最近更新 更多