首页 > 解决方案 > react中从类重构为功能钩子组件

问题描述

只是想将我的应用程序从基于类的组件重新设计为基于功能挂钩的组件,并被这个回调 setState 代码块所吸引,并且无法通过工作挂钩来实现这一点:

this.setState((prevState) => ({
    items: [
      ...prevState.items,
      {
        itemtitle: '',
        description: '',
        articlenr: '',
        amount: '',
        unit: '',
        price: '',
        taxpercentage: '',
        total: ''
      }
    ],
    showItemDetail: true
  }))

标签: reactjsfunctional-programmingcomponentsreact-hooksstate

解决方案


您是在问如何将其翻译为钩子吗?如果是这样,您将不得不发布您所在州的样子。

如果你的状态是整个对象,你可以这样做

import react, {useState} from "react";

const [items, setItems] = useState([]);

const [showItemDetail, setShowItemDetail] = useState(false)

setItems(items => [...items,
      {
        itemtitle: '',
        description: '',
        articlenr: '',
        amount: '',
        unit: '',
        price: '',
        taxpercentage: '',
        total: ''
      }
    ]
  )

setShowItemDetail(true)

推荐阅读