簡體   English   中英

不為嵌套組件調用React渲染方法

[英]React render method not called for nested component

我有這些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方法未調用。

為什么?

實際上,僅頂級組件在render方法中渲染。 當您將Bar組件放入Chart組件中時,實際上實際上只是將Bar作為Chart的屬性傳遞。

React允許您作為Chart組件的this.props.children訪問此this.props.children 因此,圖表組件的render方法應為...

render() {
    return (
        <svg>
            {this.props.children}
        </svg>
    )
}

進一步閱讀: https : //facebook.github.io/react/docs/multiple-components.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM