| 副标题[/!--empirenews.page--]  问题 React.js 已成为 Web 组件中很受欢迎的视图库。一路进化下来,它发展出了众多特性,如今已成为创建优秀的 Web 应用程序的一套完整工具。 
 它的社区经历了爆发式增长,尤其在过去的 2-3 年中,网络上出现了成千上万有关这项技术的教程。 因此,每位初学者在开始学习 React 时都应该做一件事情,那就是阅读其文档或教程进而创建他们的第一个组件,就像我在 Codeworks  上开始我的学习旅途一样: https://codeworks.me/?utm_source=medium&utm_medium=organic&utm_campaign=marco_ghiani_hackernoon_how_to_write_clean_react_components 但我的问题是:你能肯定你的 React 组件遵循了优秀实践吗?简单来说,它们是不是正常工作呢? 脏组件长什么样 为了更好地说明我的观点,让我们来看看下面的 React 组件: import React from 'react'; import './Listcomponent.css'; class Listcomponent extends React.Component {  constructor(props) {  super(props);  this.state = {  lastClickedButton: ''  };  }  render() {  return (  <div>  <hl>The last clicked button is {this.state.lastClickedButton}</hl>  <ul>  <li>  <button  onClick={() => {  this.setState({ lastClickedButton: 'Create' });  this.props.createSomething();  }}  className="my-button">  Create  </button>  </li>  <li>  <button  onClick={() => {  this.setState({ lastClickedButton: 'Read' });  this.props.readSomething();  }}  className="my-button">  Read  </button>  </li>  <li>  <button  onClick={() => {  this.setState({ lastClickedButton: 'Update' });  this.props.updateSomething();  }}  className="my-button">  Update  </button>  </li>  <li>  <button  onClick= {() => {  this.setState({ lastClickedButton: 'Destroy' });  this.props.destroySomething();  }}  className="my-button">  Destroy  </button>  </li>  </ul>  </div>  );  } } 
 一个肮脏的 React 组件 这是一个完全正常工作的 React  组件,可以在整个应用程序中多次使用。它渲染了一个按钮列表,这些按钮会触发某个事件,组件还会显示最近被点击的是哪个按钮。总之很简单。 你可能会想:“好吧……如果能用,那就没什么问题!” 但如果有人告诉你,现在这个用 62 行代码写成的组件其实用少得多的代码也能做出来呢?所以我们开始做扫除吧! 1. 优先使用 React Hooks 实现函数组件 随着 React 16.8 引入 Hooks,我们就可以在类声明中使用函数组件来构成有状态组件(如果我们需要处理任何逻辑)了。 在本文中,我们不会深入讨论类与函数组件或 React Hooks。但在 React 社区中众所周知的是,最好优先创建函数组件,尤其是现在我们有了  Hooks 这么好用的工具。 Hooks 允许你复用状态逻辑,而无需更改组件层次结构。 接下来让我们看一下第一次重构后组件的样子: import React, { useState } from 'react'; import './ListComponent.css'; const ListComponent = props => {  const [lastClickedButton, setLastClickedButton] = useState('');  return (  <div>  <hl>The last clicked button is {lastClickedButton}</hl>  <ul>  <li>  <button  onClick={() => {  setLastClickedButton('Create');  props.createSomething();  }}  className="my-button">  Create  </button>  </li>  <li>  <button  onClick={() => {  setLastClickedButton('Read');  props.ReadSomething();  }}  className="my-button">  Read  </button>  </li>  <li>  <button  onClick={() => {  setLastClickedButton('Update');  props.updateSomething();  }}  className="my-button">  Update  </button>  </li>  <li>  <button  onclick={() => {  setLastClickedButton('Destroy');  props.DestroySomething();  }}  className="my-button">  Destroy  </button>  </li>  </ul>  </div>  ); }; 
 用 React Hooks 重构成函数组件很好,我们的组件已经短一些了,我们还删除了 类 语法,但仍然需要做许多优化工作。 2. 利用好它! (编辑:宣城站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |