我花了很多時間試圖弄清楚如何阻止我的組件this.createColorBlocks()在render()方法中重新渲染。我讀過關(guān)于純組件和shouldComponentUpdate方法的帖子,但我還沒有找到一種方法,可以讓我將生成的數(shù)組添加到狀態(tài),然后在更新后映射它。我在正確的軌道上嗎?是否在渲染方法中觸發(fā) createColorMethod 方法導(dǎo)致整個組件重新渲染?我怎樣才能避免這種情況?import React, { Component } from "react";import ColorScheme from "color-scheme";import uuidv1 from "uuid/v1";import ColorBar from "../ColorBar/ColorBar";import "./PalettePicker.css";export default class PalettePicker extends Component { state = { hue: null, colorScheme: null, variation: "pastel", colors: [], editable: false }; // shouldComponentUpdate(nextProps) { // return this.props.color !== nextProps.color; // } toggleEditable = () => { const toggle = this.state.editable; this.setState({ editable: !toggle }); }; generateRandomHue = () => { return Math.floor(Math.random() * (360 + 1)); }; generateColors = () => { // The possible values are 'mono', 'contrast', 'triade', 'tetrade', and 'analogic' const { hue, colorScheme, variation } = this.state; const { pColorScheme = "mono" } = this.props; const scheme = new ColorScheme(); scheme .from_hue(hue || this.generateRandomHue()) .scheme(colorScheme || pColorScheme) .variation(variation); // return scheme.colors(); const colors = scheme.colors().map(color => { return "#" + color; }); return colors; }; createColorBlocks = () => { const generatedColors = this.generateColors(); const colors = generatedColors.splice(0, this.props.totalColors); console.log(colors); return colors.map((color, i) => { const uuid = uuidv1(); return ( <ColorBar color={color} vRotate={this.props.vRotate} number={i} key={uuid} /> ); }); };
React 阻止組件在單擊事件時重新渲染
躍然一笑
2021-09-17 13:46:41