前端 - React的setState其中一个属性的时候为什么会触发另一个组件的重新渲染?

查看:472
本文介绍了前端 - React的setState其中一个属性的时候为什么会触发另一个组件的重新渲染?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

父组件


import React from 'react';
/* 公共方法集 */
import webAPI from '../../utilies/WebAPIUtilies';
import ArrayUtilies from '../../utilies/ArrayUtilies';
/* 我的大学公共action文件 */
import MyUniversityAction from '../../actions/MyUniversityActions/MyUniversityAction';
/* 加载action */
import LoadAction from '../../actions/LoadAction/LoadAction';
/* 加载组件 */
import LoadComponent from '../../componets/CustomComponent/LoadComponent';
/* 阅读历史组件 */
import ReadHistoryComponent from './ReadHistoryComponent';

/* 加载ant框架组件 */
import Tabs from 'antd/lib/tabs';
import Row  from 'antd/lib/row';
import Col  from 'antd/lib/col';
import Carousel from 'antd/lib/carousel';
import Badge from 'antd/lib/badge'
import Progress from 'antd/lib/progress';

/* antd框架样式 */
import 'antd/dist/antd.min.css';
/* 我的大学公共样式 */
import './myUniversity.less';

const TabPane = Tabs.TabPane;

let self;

class MyBorrowedComponent extends React.Component {

    /*组件状态初始化*/
    constructor(props) {
        super(props);
        this.state = {
            readHistoryData: [
                {value: 335, name: '其他'},
                {value: 310, name: '综合性'},
                {value: 234, name: '人文社科'},
                {value: 135, name: '工业科技'},
                {value: 1548, name: '地理历史'}
            ],
            heatListData: [
                {
                    "recCtrlId": "0100795103",
                    "imageUrl": "",
                    "checkOutCount": 7,
                    "publisher": "中信出版社",
                    "title": "你的孤独虽败犹荣 = = As long as you are here",
                    "classNo1": "B821-49",
                    "booksCount": 28,
                    "authors": "刘同"
                },
                {
                    "recCtrlId": "0100431883",
                    "imageUrl": "",
                    "checkOutCount": 1,
                    "publisher": "上海人民出版社",
                    "title": "追风筝的人 = = The kite runner",
                    "classNo1": "I712.45",
                    "booksCount": 11,
                    "authors": "胡赛尼,李继宏"
                },
                {
                    "recCtrlId": "0100751881",
                    "imageUrl": "",
                    "checkOutCount": 1,
                    "publisher": "湖南文艺出版社",
                    "title": "从你的全世界路过 = = I belongeo to you : 让所有人心动的故事",
                    "classNo1": "I247.7",
                    "booksCount": 14,
                    "authors": "张嘉佳"
                },
                {
                    "recCtrlId": "0100850558",
                    "imageUrl": "",
                    "checkOutCount": 3,
                    "publisher": "湖南文艺出版社",
                    "title": "那些回不去的年少时光 . 下",
                    "classNo1": "I247.57",
                    "booksCount": 6,
                    "authors": "桐华"
                },
                {
                    "recCtrlId": "0100845577",
                    "imageUrl": "",
                    "checkOutCount": 1,
                    "publisher": "作家出版社",
                    "title": "活着",
                    "classNo1": "I247.57",
                    "booksCount": 3,
                    "authors": "余华,"
                }
            ],
            heatListPageIndex: 1, // 热门推荐分页下标
        };
        self = this;
        this.heatListPrev = this.heatListPrev.bind(this);
        this.heatListNext = this.heatListNext.bind(this);
    }

    /*组件已经生成了DOM结构时调用*/
    componentDidMount() {

    }

    /*组件从 DOM 中移除时调用*/
    componentWillUnmount() {
        self = null;
    }


    /* 热门推荐 */
    heatListPrev(from, to) {
        if (self.state.heatListPageIndex === 1) return;
        self.setState((prevState, props) => prevState.heatListPageIndex - 1);
        this.updateHeatList();
    }

    heatListNext(from, to) {
        self.setState((prevState, props) => prevState.heatListPageIndex + 1);
        this.updateHeatList();
    }

    updateHeatList() {
        webAPI.mlmbHeatList({
            pageNo: self.state.heatListPageIndex,
            pageSize: 5
        }, function (responseData) {
            if (responseData && responseData.obj && responseData.obj.length) {
                self.setState({
                    heatListData: responseData.obj
                });
            }
        });
    }


    render() {

        let colorSuccess = '#00A854';
        let colorWarning = '#FFBF00';
        let colorError = '#F04134';
        let carouselSetting = {
            dots: false,
            autoplay: false,
            arrows: true
        };

        return (
            <div className="mbc-container">
                <Row className="mbc-container-row">
                    <Col span={8} className="mbc-container-col">
                        <Tabs className="mbc-container-tabPane" defaultActiveKey="1">
                            <TabPane tab="阅读历史" key="1">
                                <ReadHistoryComponent id={"mbc-readHistory"} readHistoryData={this.state.readHistoryData}></ReadHistoryComponent>
                            </TabPane>
                        </Tabs>
                    </Col>
                </Row>
                <Row className="mbc-container-row">
                    <Col span={16} className="mbc-container-col">
                        <Tabs className="mbc-container-tabPane" defaultActiveKey="1" style={{"marginRight": "20px"}}>
                            <TabPane tab="热门推荐" key="1">
                                <Row className="carousel">
                                    <Carousel {...carouselSetting} pageIndex={self.state.heatListPageIndex} beforeChange={self.heatListPrev} afterChange={self.heatListNext}>
                                        <div className="carousel-unit">
                                            {
                                                self.state.heatListData.map(function (item) {
                                                    return (
                                                        <div className="carousel-unit-cell" key={item.recCtrlId}>
                                                            <a href="#" className="carousel-unit-imgContainer">
                                                                <img src={require('../../img/wjf.jpg')} alt="加载中..."/>
                                                            </a>
                                                            <p className="bookName">
                                                                {item.title ? item.title.split(' ')[0] : ''}
                                                            </p>
                                                        </div>
                                                    )
                                                })
                                            }
                                        </div>
                                    </Carousel>
                                </Row>
                            </TabPane>
                        </Tabs>
                    </Col>
                </Row>
            </div>
        )
    }

}

module.exports = MyBorrowedComponent;


阅读历史组件:

import React from "react";

// 引入echarts
import Echarts from "echarts/lib/echarts";

// 引入echarts的饼图组件
import EchartsPie from "echarts/lib/chart/pie";

class ReadHistoryComponent extends React.Component {

    /*组件状态初始化*/
    constructor(props) {
        super(props);
        this.setOptions = this.setOptions.bind(this);
        this.renderChart = this.renderChart.bind(this);
    }

    renderChart() {
        let data = this.props.readHistoryData; // 外部传入的data数据
        let chart = Echarts.init(document.getElementById(this.props.id)); // 初始化echarts
        let options = this.setOptions(data);
        chart.setOption(options);
    }

    // 组件生成
    componentDidMount() {
        this.renderChart();
    }


    // 组件更新
    componentWillReceiveProps() {
        this.renderChart();
    }


    // 设置echars图配置项
    setOptions(data) {
        return {
            series: [
                {
                    name: '访问来源',
                    type: 'pie',
                    radius: '60%',
                    center: ['50%', '55%'],
                    data: data,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        }
    }

    render() {
        return (
            <div id={this.props.id} style={{"height": "200px"}}></div>
        )
    }

}

module.exports = ReadHistoryComponent;






我在父组件中调用了 updateHeatList 方法去更新其中一个字组件(热门推荐)


self.setState({
    heatListData: responseData.obj
});



讲道理我只设置了其中一个 heatListData属性而已,为什么这个时候回触发 阅读历史 组件的渲染?

补充:来自官网的描述

解决方案

说一点,只要子组件从父组件里获取了一个prop,只要父组件重新render,无论prop有无改变,都会出发子组件的render。

要知道,state是immutable的,每次setState都会用一个新的state去覆盖掉原来的state,所以其实对于子组件来说,只是值没变而已。

这篇关于前端 - React的setState其中一个属性的时候为什么会触发另一个组件的重新渲染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆