React-admin:如何实现自动保存/后台保存功能?

Jas*_*son 6 redux-form react-admin

如何使用 react-admin 实现自动保存/后台保存功能?

我在编辑富文本输入字段时想要一个功能,例如富文本,后台保存会将我的文本推送到服务器,而无需触摸我的焦点和编辑位置。

我尝试使用 EditController 和 SimpleFrom,这将重新渲染表单并从服务器获取记录器,并失去焦点和编辑位置。请问有什么例子或建议吗?

Lar*_*erg 2

我构建了一个名为的嵌入式组件EditFormAutoSave,您可以简单地将其添加到现有组件中EditForm以进行自动保存。它会在短暂的不活动等待间隔后以及卸载编辑表单时保存所有更改的“脏”字段,以防止任何数据丢失。

重要提示:编辑表单需要设置redirect={false}为防止在成功自动保存后发生重定向。

用法

const YourResourceEdit = props => (
  <Edit mutationMode="optimistic" {...props}>
    <SimpleForm redirect={false} toolbar={<EditToolbar />}>
      <EditFormAutoSave waitInterval={2000} />
      <TextInput source="someFieldName" />
      ...
    </SimpleForm>
  </Edit>
)
Run Code Online (Sandbox Code Playgroud)

EditFormAutoSave.js

import _ from 'lodash'
import {useEffect, useRef} from 'react'
import {useEditContext} from 'react-admin'
import {useFormState} from 'react-final-form'

const EditFormAutoSave = ({waitInterval = 1000}) => {
  const {dirty, valid, values} = useFormState({subscription: {
    dirty: true, valid: true, values: true,
  }})
  const {save, saving} = useEditContext()
  const shouldSaveRef = useRef()
  const saveDebouncedRef = useRef()
  /*
   * Determine whether 'save' should be called by any of the following effects. Use a
   * 'ref' instead of a 'state' so that the an unmount effect can be set up which musn't
   * have state dependencies.
   */
  useEffect(() => {
    shouldSaveRef.current = dirty && valid && !saving
  }, [dirty, saving, valid])
  /*
   * Debounce the 'save()' function and store it in a 'ref' for the same reason as
   * above (it needs to be called on unmount which musn't have state dependencies).
   */
  useEffect(() => {
    saveDebouncedRef.current = _.debounce(save, waitInterval)
  }, [save, waitInterval])
  /*
   * Whenever the form data got dirty, schedule saving data
   */
  useEffect(() => {
    if (shouldSaveRef.current) {
      saveDebouncedRef.current({...values}, /* redirectTo= */false)
    }
  }, [dirty, saving, valid, values])
  /*
   * On component unmount submit any unsubmitted changes so that changed ("dirty") fields
   * get persisted. Said differently this effects prevents data loss of unsaved changes.
   */
  useEffect(() => () => {
    shouldSaveRef.current && saveDebouncedRef.current.flush()
  }, [])
}

export default EditFormAutoSave
Run Code Online (Sandbox Code Playgroud)