我有这些React类
class App extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { dispatch } = this.props;
var props = this.props;
dispatch(fetchDistricts('California'));
}
render() {
return (
<div class="app">
<Chart width={this.props.width}
height={this.props.height}>
<Bar data={this.props}
width={this.props.width}
height={this.props.height}>
</Bar>
</Chart>
</div>
);
}
};
图表看起来像这样
export default class Chart extends React.Component {
render() {
return (
<svg width={this.props.width}
height={this.props.height}>
</svg>
);
}
};
和酒吧看起来像这样
export default class Bar extends React.Component {
shouldComponentUpdate(nextProps) {
debugger
return this.props.data !== nextProps.data;
}
render() {
debugger
let props = this.props;
let data = props.data.map((d) =>
{
return d.y;
}
);
let yScale = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, this.props.height]);
let xScale = d3.scale.ordinal()
.domain(d3.range(this.props.data.length))
.rangeRoundBands([0, this.props.width], 0.05);
let bars = data.map((point, i) => {
var height = yScale(point),
y = props.height - height,
width = xScale.rangeBand(),
x = xScale(i);
return (
<Rect height={height}
width={width}
x={x}
y={y}
key={i}>
</Rect>
);
});
return (
<g>{bars}</g>
);
}
};
没有调用Bars中的调试器 - 不调用render方法。
为什么呢?
答案 0 :(得分:4)
实际上只在渲染方法中渲染顶级组件。当您将Bar组件放入Chart组件中时,您实际上只是将Bar作为Chart的属性传递。
React允许您以图表组件的this.props.children
形式访问它。因此,图表组件的渲染方法应该是......
render() {
return (
<svg>
{this.props.children}
</svg>
)
}
进一步阅读:https://facebook.github.io/react/docs/multiple-components.html