簡體   English   中英

如何在 Object Literals 中調用 void function

[英]How to invoke void function in Object Literals

當 function 有返回值時它起作用,如果它為空則不起作用。 當它是對象的值時,如何像這樣調用 void function?

帶有 if-else 語句的代碼:

const handlePageChange = (number, type) => {

      const handlePage = () => setCurrentPage(number)
      const handleAllLeft = () => setCurrentPage(1)
      const handleAllRight = () => setCurrentPage(Math.ceil(data?.length / dataPerPage))
      const handleLeft = () => {
        if(currentPage === 1) setCurrentPage(1)
        else setCurrentPage(currentPage - 1)
      }
      const handleRight = () => {
        if(currentPage === Math.ceil(data?.length / dataPerPage)) setCurrentPage(Math.ceil(data?.length / dataPerPage))
        else setCurrentPage(currentPage + 1)
      }
      
      if(type === "page") handlePage()
      if(type === "all-left") handleAllLeft()
      if(type === "all-right") handleAllRight()
      if(type === "left") handleLeft()
      if(type === "right") handleRight()
    }

帶有 object 文字的代碼:

const renderPagination = () => {
    const pageNumbers = []

    for (let i = 1; i <= Math.ceil(data?.length / dataPerPage); i++) {
      pageNumbers.push(i)
    }


    const handlePageChange = (number, type) => {

      const handlePage = () => setCurrentPage(number)
      const handleAllLeft = () => setCurrentPage(1)
      const handleAllRight = () => setCurrentPage(Math.ceil(data?.length / dataPerPage))
      const handleLeft = () => {
        if(currentPage === 1) setCurrentPage(1)
        else setCurrentPage(currentPage - 1)
      }
      const handleRight = () => {
        if(currentPage === Math.ceil(data?.length / dataPerPage)) setCurrentPage(Math.ceil(data?.length / dataPerPage))
        else setCurrentPage(currentPage + 1)
      }


      const obj = {
        "page": handlePage(),
        "all-left": handleAllLeft(),
        "all-right": handleAllRight(),
        "left": handleLeft(),
        "right": handleRight()
      }

      return obj[type] || null
    }

試過state更新后返回null,還是沒有變化。

與您的方法不同的是,當您分配 object 值時,第二個執行所有功能

 const obj = {
        "page": handlePage(),
        "all-left": handleAllLeft(),
        "all-right": handleAllRight(),
        "left": handleLeft(),
        "right": handleRight()
      }

如果你想要與第一個代碼中相同的執行,你可以分配函數,然后在返回時執行你想要的

   const obj = {
        "page": handlePage,
        "all-left": handleAllLeft,
        "all-right": handleAllRight,
        "left": handleLeft,
        "right": handleRight
      }

    return obj[type]() || null // <-- See extra parenthesis here

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM