|
| 1 | +# 13 ShouldUpdate |
| 2 | + |
| 3 | +En este ejemplo vamos a mejorar el rendimiento de renderizado con 'shouldComponentUpdate'. |
| 4 | + |
| 5 | +Vamos a implementar un widget de satisfacción del cliente, basado en caras o emoticonos. |
| 6 | +Este aceptará valores en un rango de 0 a 500, y las caras tendrán un rango de valores de |
| 7 | +0..100, 100..200, 200..300, 300..400, 400..500. Solo lanzaremos las opciones de render cuando |
| 8 | +los valores salten al próximo o al rango previo. |
| 9 | + |
| 10 | +Tomaremos como punto de partida el ejemplo _03 State_: |
| 11 | + |
| 12 | +Resumen de pasos: |
| 13 | + |
| 14 | +- Eliminar los componentes _hello_ y _nameEdit_ (limpieza de app). |
| 15 | +- Copiar bajo el directorio _content_ los 4 png's que contienen los smileys. |
| 16 | +- Create bajo el directorio _content_ un fichero _site.css_ y definir allí los estilos para los smileys. |
| 17 | +- Crear un componente smily. |
| 18 | +- Añadir al estado de la app una entrada currentValue, pasarle el cntrol y además añadirle un slider |
| 19 | +para configurarlo. |
| 20 | +- Vamos a añadirle una optimización... componentshouldupdate. |
| 21 | + |
| 22 | +## Prerrequisitos |
| 23 | + |
| 24 | +Instalar [Node.js and npm](https://nodejs.org/en/) (v6.6.0 or newer) si no están previamente instalados. |
| 25 | + |
| 26 | + |
| 27 | +## Pasos para construirlo: |
| 28 | + |
| 29 | +- Copiar el contenido desde _03 State_ y ejecutarlo: |
| 30 | + |
| 31 | + ``` |
| 32 | + npm install |
| 33 | + ``` |
| 34 | + |
| 35 | +- Eliminar _nameEdit.js_ y _hello.jsx_, quitarlos también de _app.jsx_: |
| 36 | + |
| 37 | + ```jsx |
| 38 | + import * as React from 'react'; |
| 39 | + |
| 40 | + export class App extends React.Component { |
| 41 | + constructor(props) { |
| 42 | + super(props); |
| 43 | + } |
| 44 | + |
| 45 | + render() { |
| 46 | + return ( |
| 47 | + <div /> |
| 48 | + ); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + ``` |
| 53 | +- Crear una carpeta _src/content_ y copiar los 5 smiley (puedes copiarlos desde la carpeta de su |
| 54 | +implementación en github). |
| 55 | + |
| 56 | +- Vamos a crear un archivo css: _src/content/site.css_ y añadimos los estilos de los smileys: |
| 57 | + |
| 58 | + ```css |
| 59 | + .very-dissatisfied { |
| 60 | + width:100%; |
| 61 | + height:80px; |
| 62 | + background:url('./one.png') no-repeat;; |
| 63 | + } |
| 64 | + |
| 65 | + .somewhat-dissatisfied { |
| 66 | + width:100%; |
| 67 | + height:80px; |
| 68 | + background:url('./two.png') no-repeat; |
| 69 | + } |
| 70 | + |
| 71 | + .neither { |
| 72 | + width:100%; |
| 73 | + height:80px; |
| 74 | + background:url('./three.png') no-repeat; |
| 75 | + } |
| 76 | + |
| 77 | + .somewhat-satisfied { |
| 78 | + width:100%; |
| 79 | + height:80px; |
| 80 | + background:url('./four.png') no-repeat; |
| 81 | + } |
| 82 | + |
| 83 | + .very-satisfied { |
| 84 | + width:100%; |
| 85 | + height:80px; |
| 86 | + background:url('./five.png') no-repeat; |
| 87 | + } |
| 88 | + ``` |
| 89 | + |
| 90 | +-En _webpack.config.js_ añadimos un nuevo punto de entrada _css_: |
| 91 | + |
| 92 | + ```javascript |
| 93 | + entry: [ |
| 94 | + './main.jsx', |
| 95 | + '../node_modules/bootstrap/dist/css/bootstrap.css', |
| 96 | + './content/site.css', |
| 97 | + ], |
| 98 | + ``` |
| 99 | + |
| 100 | +- Necesitamos añadir un loder para manejar imágenes en _webpackconfig.js_: |
| 101 | + |
| 102 | + ```javascript |
| 103 | + { |
| 104 | + test: /\.(png|jpg)$/, |
| 105 | + exclude: /node_modules/, |
| 106 | + loader: 'url-loader?limit=10000' |
| 107 | + }, |
| 108 | + ``` |
| 109 | + |
| 110 | +- Vamos a crear un componente simple _faceComponent_ bajo _src_, vamos a comenzar con añadir |
| 111 | +algo hardcodeado en el fichero _src/face.jsx_: |
| 112 | + |
| 113 | + ```jsx |
| 114 | + import * as React from 'react'; |
| 115 | + import { } from '../src/content/site.css'; |
| 116 | + const FaceComponent = (props) => ( |
| 117 | + <div className="somewhat-satisfied" /> |
| 118 | + ); |
| 119 | + |
| 120 | + FaceComponent.propTypes = { |
| 121 | + level: React.PropTypes.number.isRequired, |
| 122 | + }; |
| 123 | + |
| 124 | + export default FaceComponent; |
| 125 | + ``` |
| 126 | + |
| 127 | +- Vamos a hacer un pequeño test en _app.jsx_ |
| 128 | + |
| 129 | + ```jsx |
| 130 | + import * as React from 'react'; |
| 131 | + import FaceComponent from './face'; |
| 132 | + |
| 133 | + export class App extends React.Component { |
| 134 | + constructor(props) { |
| 135 | + super(props); |
| 136 | + } |
| 137 | + |
| 138 | + render() { |
| 139 | + return ( |
| 140 | + <div> |
| 141 | + <FaceComponent level={100} /> |
| 142 | + </div> |
| 143 | + ); |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + ``` |
| 148 | + |
| 149 | +- Vamos a añadir un check point y ejecutamos el ejemplo: Chequeamos que funciona como debe ser: |
| 150 | + |
| 151 | + ``` |
| 152 | + npm start |
| 153 | + ``` |
| 154 | + |
| 155 | +- Ahora es tiempo de enlazar la propiedad con la cara apropiada, vamos a crear una función de estilos |
| 156 | +para ello, en el _face.jsx_ |
| 157 | + |
| 158 | + ```jsx |
| 159 | + import * as React from 'react'; |
| 160 | + import { } from '../src/content/site.css'; |
| 161 | + // eslint-disable-next-line import/prefer-default-export |
| 162 | + const FaceComponent = (props) => { |
| 163 | + function setSatisfactionClass(level) { |
| 164 | + if (level < 100) { |
| 165 | + return 'very-dissatisfied'; |
| 166 | + } |
| 167 | + |
| 168 | + if (level < 200) { |
| 169 | + return 'somewhat-dissatisfied'; |
| 170 | + } |
| 171 | + |
| 172 | + if (level < 300) { |
| 173 | + return 'neither'; |
| 174 | + } |
| 175 | + |
| 176 | + if (level < 400) { |
| 177 | + return 'somewhat-satisfied'; |
| 178 | + } |
| 179 | + |
| 180 | + return ('very-satisfied'); |
| 181 | + } |
| 182 | + |
| 183 | + return ( |
| 184 | + <div className={setSatisfactionClass(props.level)} /> |
| 185 | + ); |
| 186 | + }; |
| 187 | + |
| 188 | + FaceComponent.propTypes = { |
| 189 | + level: React.PropTypes.number.isRequired, |
| 190 | + }; |
| 191 | + |
| 192 | + export default FaceComponent; |
| 193 | + |
| 194 | + ``` |
| 195 | +- En _app.jsx_ vamos a añadir una variable de estado para almacenar el nivel de |
| 196 | +satisfacción actual, además un slider que permita que el usuario lo actualice. |
| 197 | + |
| 198 | + ```jsx |
| 199 | + import * as React from 'react'; |
| 200 | + import FaceComponent from './face'; |
| 201 | + |
| 202 | + export class App extends React.Component { |
| 203 | + constructor(props) { |
| 204 | + super(props); |
| 205 | + |
| 206 | + this.state = { satisfactionLevel: 300 }; |
| 207 | + } |
| 208 | + |
| 209 | + render() { |
| 210 | + return ( |
| 211 | + <div> |
| 212 | + <input |
| 213 | + type="range" |
| 214 | + min="0" |
| 215 | + max="500" |
| 216 | + value={this.state.satisfactionLevel} |
| 217 | + onChange={event => |
| 218 | + this.setState({ satisfactionLevel: parseInt(event.target.value, 10) }) |
| 219 | + } |
| 220 | + /> |
| 221 | + <br /> |
| 222 | + <span>{this.state.satisfactionLevel}</span> |
| 223 | + <br /> |
| 224 | + <FaceComponent level={this.state.satisfactionLevel} /> |
| 225 | + </div> |
| 226 | + ); |
| 227 | + } |
| 228 | + } |
| 229 | + |
| 230 | + ``` |
| 231 | + |
| 232 | +- Ejecutemos el ejemplo: |
| 233 | + |
| 234 | + ``` |
| 235 | + npm start |
| 236 | + ``` |
| 237 | + |
| 238 | +- Añadiremos una optimización, solo lanzaremos el render cuando el nivel |
| 239 | +de satisfacción cambie de rango, necesitamos cambiar el componente a un componente que meneje |
| 240 | +el estado: |
| 241 | + |
| 242 | + ```jsx |
| 243 | + import * as React from 'react'; |
| 244 | + import { } from '../src/content/site.css'; |
| 245 | + |
| 246 | + class FaceComponent extends React.Component { |
| 247 | + setSatisfactionClass(level) { |
| 248 | + if (level < 100) { |
| 249 | + return 'very-dissatisfied'; |
| 250 | + } |
| 251 | + |
| 252 | + if (level < 200) { |
| 253 | + return 'somewhat-dissatisfied'; |
| 254 | + } |
| 255 | + |
| 256 | + if (level < 300) { |
| 257 | + return 'neither'; |
| 258 | + } |
| 259 | + |
| 260 | + if (level < 400) { |
| 261 | + return 'somewhat-satisfied'; |
| 262 | + } |
| 263 | + |
| 264 | + return ('very-satisfied'); |
| 265 | + } |
| 266 | + |
| 267 | + shouldComponentUpdate(nextProps, nextState) { |
| 268 | + const rangeChange = [100, 200, 300, 400]; |
| 269 | + |
| 270 | + let index = 0; |
| 271 | + let isRangeChange = false; |
| 272 | + while (!isRangeChange && index < rangeChange.length) { |
| 273 | + isRangeChange = |
| 274 | + (this.props.level < rangeChange[index] && |
| 275 | + nextProps.level >= rangeChange[index]) || |
| 276 | + (this.props.level > rangeChange[index] && |
| 277 | + nextProps.level <= rangeChange[index]); |
| 278 | + |
| 279 | + index += 1; |
| 280 | + } |
| 281 | + |
| 282 | + return isRangeChange; |
| 283 | + } |
| 284 | + render() { |
| 285 | + return ( |
| 286 | + <div className={this.setSatisfactionClass(this.props.level)} /> |
| 287 | + ); |
| 288 | + } |
| 289 | + } |
| 290 | + |
| 291 | + FaceComponent.propTypes = { |
| 292 | + level: React.PropTypes.number.isRequired, |
| 293 | + }; |
| 294 | + |
| 295 | + export default FaceComponent; |
| 296 | + |
| 297 | + ``` |
| 298 | + |
| 299 | +- Ahora si ponemos un breakpoint en el render del faceComponent podemos ver que |
| 300 | +el render solo es lanzado cuando cambiamos el rango de satisfacción (e.g. 99 to 100). |
| 301 | + |
| 302 | + ``` |
| 303 | + npm start |
| 304 | + ``` |
0 commit comments