如何在 React.js 项目中将类组件转换为功能组件?

在我观看的项目中,他们使用类组件,但我想使用钩子使用功能组件来执行这些操作。你们能如何帮助我?我尝试了很多次,但无法完成这个翻译。我还在努力


我的代码(导入的数据是“成分”):


class App extends React.Component {

  constructor(props) {

    super(props)

    this.state = {

      ingredients: [],

      totalPrice: 0

    }


    this.addIngredients = this.addIngredients.bind(this)

    this.removeIngredients = this.removeIngredients.bind(this)

    this.calculateTotal = this.calculateTotal.bind(this)

  }


  addIngredients(product) {

    this.setState({

      ingredients: [...this.state.ingredients].concat([

        { ...product, displayId: Math.random() }

      ])

    })

  }


  removeIngredients(product) {

    const selectedProduct = this.state.ingredients.find((ingredient) => {

      return ingredient.name === product.name

    })


    const targetId = selectedProduct.displayId


    this.setState({

      ingredients: this.state.ingredients.filter((ingredient) => {

        return ingredient.displayId !== targetId

      })

    })

  }


  calculateTotal() {

    let total = 4

    this.state.ingredients.forEach((item) => {

      total += item.price

    })

    return total.toFixed(2)

  }


  render() {

    return (

      <div>

        <Hamburger ingredients={this.state.ingredients} />

        <TotalPrice total={this.calculateTotal} />

        <ItemList

          items={ingrediends}

          addIngredients={this.addIngredients}

          removeIngredients={this.removeIngredients}

          selectedIngredients={this.state.ingredients}

        />

      </div>

    )

  }

}

export default App


慕田峪7331174
浏览 105回答 1
1回答

慕少森

我无法测试它,但对你来说是一个好的开始,我使用 ES6 语法......import React, { useState } from 'react';import { Hamburger, TotalPrice, ItemList } from './SuperComponents.jsx';const App = () => {    const [ingredients, setIngredients] = useState([]);    // You are not using this state    // const [totalPrice, setTotalPrice] = useState(0);    const addIngredients = (product) => {        setIngredients([...ingredients, { ...product, displayId: Math.random() }]);    };    const removeIngredients = (product) => {        const selectedProduct = ingredients.find(            (ingredient) => ingredient.name === product.name        );        const { targetId } = selectedProduct;        setIngredients(            ingredients.filter((ingredient) => ingredient.displayId !== targetId)        );    };    const calculateTotal = () => {        let total = 4;        ingredients.forEach((item) => (total += item.price));        return total.toFixed(2);    };    return (        <>            <Hamburger ingredients={ingredients} />            <TotalPrice total={() => calculateTotal()} />            <ItemList                items={ingredients}                addIngredients={(i) => addIngredients(i)}                removeIngredients={(i) => removeIngredients(i)}                selectedIngredients={ingredients}            />        </>    );};export default App;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript