我一个月前就开始和React合作了.现在我正在构建一步一步的应用程序.我有我的代码,但我觉得我可以更清洁它. 有人可以检查这段代码..并给我建议,我可以学习和提高我的React技能? 我的
有人可以检查这段代码..并给我建议,我可以学习和提高我的React技能?
我的代码有效,但想知道这是否更清洁:
import React, { Component } from 'react'; import axios from 'axios'; class App extends Component { state = { fragrances: [] } componentDidMount() { const URI = 'http://localhost:1337/'; const post_type = 'fragrances'; axios .get(`${URI + post_type}`) .then(response => { const fragrances = response.data; this.setState({ fragrances }); }) .catch(error => { console.log('An error occurred:', error); }); } render() { const { fragrances } = this.state; return ( <React.Fragment> <div className="row"> { fragrances.map((fragrance, index) => { const url = 'http://localhost:1337'; const image = fragrance.Image; const name = fragrance.Name; const category = fragrance.Category; const desc = fragrance.Description; return ( <div key={index} className="col-sm-6 col-xs-12"> <div className="fragrance"> { image ? <img className="fragrance__image" src={url + image.url} alt={name} /> : <h4>Geen foto beschikbaar.</h4>} { name ? <h2 className="fragrance__title">{name}</h2> : 'Geen titel aanwezig.'} { category ? <span class="fragrance__category">{category}</span> : ' '} { desc ? <p className="fragrance__description">{desc}</p> : 'Geen omschrijving aanwezig.'} </div> </div> ) }) } </div> </React.Fragment> ) } } export default App;
提前致谢.
创建< Fragrance />组件会使它更干净,加上使用ES6解构.此外,片段在列表中是不必要的,因为它被包装在单个< div className =“row”>中:.... render() { const { fragrances } = this.state; const url = 'http://localhost:1337'; return ( <div className="row"> {fragrances.map((fragrance, index) => { const { Image: image, Name: name, Category: category, Description: desc } = fragrance; return ( <Fragrance key={index} image={image} name={name} category={category} desc={desc} /> ) }) } </div> ) } ...
Fragrance.js
const Fragance = ({name, category, image, desc }) => ( <div key={index} className="col-sm-6 col-xs-12"> <div className="fragrance"> { image ? <img className="fragrance__image" src={url + image.url} alt={name} /> : <h4>Geen foto beschikbaar.</h4>} { name ? <h2 className="fragrance__title">{name}</h2> : 'Geen titel aanwezig.'} { category ? <span class="fragrance__category">{category}</span> : ' '} { desc ? <p className="fragrance__description">{desc}</p> : 'Geen omschrijving aanwezig.'} </div> </div> ) export default Fragrance;