我花了很多时间试图弄清楚如何阻止我的组件在this.createColorBlocks()
方法中重新呈现render()
。我已经阅读了有关纯组件和shouldComponentUpdate
方法的文章,但我一直无法找出一种方法,该方法可以让我将生成的数组添加到状态,然后在更新后对其进行映射。
我走对了吗?是否在render方法内部触发了createColorMethod方法,导致整个组件重新渲染?如何避免这种情况?
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}
/>
);
});
};
render() {
const editBlockStyles = {
transform: "translateY(-15px)"
};
const colors = this.createColorBlocks();
return (
<section className="PalettePicker">
<div className="colors-section">{colors}</div>
<div className="button-bar">
// I believe this onClick event is causing the rerender.
<button className="primary-btn" onClick={this.toggleEditable}>
Edit Colors
</button>
<button className="primary-btn">Save</button>
</div>
</section>
);
}
}
答案 0 :(得分:2)
react中的每个状态更新都会导致重新渲染,并且当您的onClick
切换editable
标志时,每次单击按钮时,组件都会重新渲染。如果您不想每次都重新生成颜色,则需要将该功能移出render()
(例如,移至componentDidMount()
,就像John Ruddell suggested一样)。< / p>