Reactjs 功能组件常用逻辑抽取

时间:2021-07-18 05:40:08

标签: javascript reactjs react-functional-component

我有一些带有一些常见变量和函数的功能组件。请参阅下文。

const Customer = () => {
   const [isReleased, setIsReleased] = useState(false)

   const release = () => {
        setIsReleased(true)
   }
}

const Order = () => {
   const [isReleased, setIsReleased] = useState(false)

   const release = () => {
        setIsReleased(true)
   }
}

从上面的代码片段可以看出,release()函数有共同的逻辑。它访问组件的变量/函数。

有没有办法将这个 release() 函数移动到一个公共文件并从每个组件导入它?

请注意,release() 方法应该能够访问调用方的作用域变量和函数。

更新

下面是release()函数的实际内容。我已经把 this. 表示它指的是调用者中的变量/函数。

const release = () => {
  if (action === "new") {
    history.push(`/customers/new`)
  } else if (action === "save") {
    (async () => {
      try {
        if (this.dataMode === "new") {
          this.setMessage()
          this.setFormStatus("updating")
          let _res = await this.customer_api_create(this.formData)
          if ((_res.status === 200) && (_res.data.status === "success")) {
            this.setFormStatus()
            history.replace({ pathname: `/customers/${_res.data.data[0].id}` })
          }
        } else if (this.dataMode === "edit") {
          this.setFormStatus("updating")
          this.setMessage()
          let _res = await this.customer_api_update(this.formData)
          if ((_res.status === 200) && (_res.data.status === "success")) {
            this.setFormStatus()
            this.setMessage({ type: "info", text: "Saved" })
            this.setFormData(_res.data.data[0])
          }
        }
      } catch (e) {
        this.openMessageBox({
          prompt: e.response.data.message,
          type: this.constants.app.MessageBoxType.MB_Error,
          buttons: this.constants.app.MessageBoxButton.MB_Ok,
          show: true,
          setResult: () => console.log(this.constants.app.MessageBoxResult.MB_Ok)
        })
        this.setFormStatus("updating_error")
      }
    })();
  } else if (action === "del") {
    this.openMessageBox({
      prompt: `{ "": ["Are you sure you want to delete context customer?"] }`,
      type: this.constants.app.MessageBoxType.MB_Warning,
      buttons: this.constants.app.MessageBoxButton.MB_YesNo,
      show: true,
      setResult: (val) => {
        this.openMessageBox({ show: false })
        this.setShouldRecordDeleted(val)
      }
    })
  }
}

2 个答案:

答案 0 :(得分:-1)

您可以在不同的文件中声明函数 release 并将 setIsReleased 方法作为参数传递

import {release} from 'release';  

const Customer = () => {
       const [isReleased, setIsReleased] = useState(false)
       release(setIsReleased)
    }

在你的 release.js 文件中

export const release = (setIsReleased) => {
   setIsReleased(true)
}

答案 1 :(得分:-1)

也许回调可以解决问题,这个怎么样?

anotherfile.js

    const release = (param, setter) => {
        if (true){
            setter(true)
        }
    }

你的文件.js

    import {release} from "anotherfile"
    const Customer = () => {
       const [isReleased, setIsReleased] = useState(false)
       release([parameter],setIsReleased)
    }