【问题标题】:shouldComponentUpdate not working in child component React jsshouldComponentUpdate 在子组件 React js 中不起作用
【发布时间】:2018-04-19 07:53:32
【问题描述】:

当我使用父组件中的 setState 更新我的状态时,我的子组件得到渲染(因为 props 发生变化)
父组件

    addonsHandler =(addons) =>{

            this.setState({addons:addons}, () => {
                // console.log(this.state.addons);
            });

        };
render() {

        return (
            <div>
                <Row>
                    <Col span={15} offset={2}>
                        <AntForm pickupHandler= {this.pickupHandler} dropHandler={this.dropHandler} addonsHandler={this.addonsHandler} ambulanceTypeHandler={this.ambulanceTypeHandler}/>
                        <Button type="primary" onClick={this.drop} >Drop</Button>
                        <Button type="primary" onClick={this.calculateRoute}>Direction</Button>
                        {/*<div id="map" style={{height: "600px"}}></div>*/}
                        <Map onRef={ref => (this.MapRef = ref)} />
                    </Col>
                    <Col span={6} offset={1}>

                        <BookingDetails  addons={this.state.addons} price={this.addonObj} ambulaceType={this.state.AmbulanceType} VehiclePrice={this.ambulacneTypeObj}  />

                    </Col>
                </Row>
                <Row>
                    <Col span={15} offset={2}>

                    </Col>
                </Row>

            </div>

        );
    }

所以我想在 addons 父组件状态发生变化时仅停止渲染 Map 组件

所以我在 Map 组件中使用了shouldComponentUpdate,但它并没有停止渲染到组件

shouldComponentUpdate(nextProps, nextState) {
        return false;
    }

【问题讨论】:

标签: javascript reactjs react-component


【解决方案1】:

shouldComponentUpdate() 影响父组件。如果它返回 true,父组件将被重新渲染。 所以,我认为你应该将 shouldComponentUpdate() 移到 BookingDetails 组件中。

【讨论】:

  • 但我需要其他组件中的状态,所以其他组件应该呈现
猜你喜欢
  • 2018-11-04
  • 2020-04-23
  • 2022-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 1970-01-01
  • 2016-12-27
相关资源
最近更新 更多