react 组件封装原则_编写 React 组件要点:单一责任原则

思维导图

什么是单一原则单一责任原则 SRP(Single responsibility principle) 是一种计算机编程原理,它规定每个模块或类应该对软件提供的单个功能负责。

在 React 里单一责任原则要求组件改变时只有一个原因。

React 组件使用单一责任原则时,当它改变时只会有一个原因,做一件事就会更简单。

多责任陷阱直接编码,不划分结构

写一个大组件,不划分组件

对 callback、props、fetch 都不拆分

反模式、上帝组件。

多见于 , , , 大量代码

React 单一责任原则

设想一个组件import axios from 'axios';

// 组件具有多个职责class Weather extends Component {

constructor(props) {     super(props);     this.state = { temperature: 'N/A', windSpeed: 'N/A' };

}

render() {     const { temperature, windSpeed } = this.state;     return (       

Temperature: {temperature}°C
Wind: {windSpeed}km/h

);

}

componentDidMount() {

axios.get('http://weather.com/api').then(function(response) {       const { current } = response.data;

this.setState({         temperature: current.temperature,         windSpeed: current.windSpeed

})

});

}

}这个组件有两个方式会改变:(setState 和 render 会导致组件渲染)

1 componentDidMount() 请求 http://weather.com/api 获取数据时 this.setState

2 在 render() 里渲染数据时

改写当前组件import axios from 'axios';

// 当前组件只负责获取数据class WeatherFetch extends Component {

constructor(props) {     super(props);     this.state = { temperature: 'N/A', windSpeed: 'N/A' };

}

render() {     const { temperature, windSpeed } = this.state;     return (       

);

}

async componentDidMount() {

const response = await axios.get('http://weather.com/api');

const { current } = response.data;

this.setState({

temperature: current.temperature,

windSpeed: current.windSpeed

});

}

}// 组件只负责展示数据,展示逻辑可写在内部  function WeatherInfo({ temperature, windSpeed }) {

const windInfo = windSpeed === 0 ? 'calm' : `${windSpeed} km/h`;   return (     

Temperature: {temperature}°C
Wind: {windInfo}

);

}

HOC 高阶组件借用高阶函数的概念:高阶组件是一个函数,入参接受一个组件返回值也是一个组件

属性代理 props proxy高阶组件为封装的组件传递新的 props 或者改变现有的 props,这种方式称为属性代理function withNewFunctionality(WrappedComponent) {

return class NewFunctionality extends Component {

render() {      const newProp = 'Value';      const propsProxy = {

...this.props,         // Alter existing prop:

ownProp: this.props.ownProp + ' was modified',         // Add new prop:

newProp

};      return ;

}

}

}

const MyNewComponent = withNewFunctionality(MyComponent);

渲染劫持 render highjacking通过更改组件 render 方法来改变组件的渲染方式,这种方式称为渲染劫持function withModifiedChildren(WrappedComponent) {

return class ModifiedChildren extends WrappedComponent {

render() {      const rootElement = super.render();      const newChildren = [

...rootElement.props.children,

// Insert a new child:

New child

];      return cloneElement(

rootElement,

rootElement.props,

newChildren

);

}

}

}const MyNewComponent = withModifiedChildren(MyComponent);

HOC 高阶组件单一责任原则

先定义多重责任组件class PersistentForm extends Component {

constructor(props) {    super(props);    this.state = { inputValue: localStorage.getItem('inputValue') };    this.handleChange = this.handleChange.bind(this);    this.handleClick = this.handleClick.bind(this);

}

render() {    const { inputValue } = this.state;    return (      

onChange={this.handleChange}/>

Save to storage

);

}

handleChange(event) {

this.setState({

inputValue: event.target.value

});

}

handleClick() {

localStorage.setItem('inputValue', this.state.inputValue);

}

}constructor 内进行数据初始化

button 点击时保存数据

input 内容改变时更新组件状态

抽离出保存数据逻辑class PersistentForm extends Component {

constructor(props) {    super(props);    this.state = { inputValue: props.initialValue };    this.handleChange = this.handleChange.bind(this);    this.handleClick = this.handleClick.bind(this);

}

render() {    const { inputValue } = this.state;    return (      

onChange={this.handleChange}/>

Save to storage

);

}

handleChange(event) {

this.setState({

inputValue: event.target.value

});

}

handleClick() {

this.props.saveValue(this.state.inputValue);

}

}改写组件,使数据初始化和保存功能都由 props 传递

此组件现在只负责 input 的数据变化,数据和保存逻辑都由外部提供

编写可复用的单一责任原则的高阶组件// 给函数传递两个参数,一个是数据获取的 key 值,一个是存储函数function withPersistence(storageKey, storage) {  // 高阶组件函数

return function(WrappedComponent) {    return class PersistentComponent extends Component {      constructor(props) {        super(props);        this.state = { initialValue: storage.getItem(storageKey) };

}

render() {         return (           

initialValue={this.state.initialValue}

saveValue={this.saveValue}

{...this.props}

/>

);

}

saveValue(value) {

storage.setItem(storageKey, value);

}

}

}

}// 调用方式const LocalStoragePersistentForm

= withPersistence('key', localStorage)(PersistentForm);隔离了数据操作和展示操作

数据操作可以通过高阶函数传参改变存储 API 或 key 值

符合单一责任原则:允许在隔离中进行修改,从而较少影响系统的其他部分。

作者:豹不易

链接:https://www.jianshu.com/p/78c8d87cc834

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值