Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 推送到道具阵列时,将重新渲染所有子组件_Reactjs - Fatal编程技术网

Reactjs 推送到道具阵列时,将重新渲染所有子组件

Reactjs 推送到道具阵列时,将重新渲染所有子组件,reactjs,Reactjs,我有一个名为roles的数组,我在其中循环并创建子组件。当我将一个项目推送到该数组时,所有子组件都在重新渲染(基于渲染方法中的console.log) 我认为react有智能虚拟dom diffing,其中只更新更改的项。那么,为什么所有的道具都会被重新渲染,甚至当一个额外的道具附加到数组中时,所有的子道具都保持不变呢?在错误地更新阵列的情况下,我是否做错了什么 var Child=React.createClass({ render:function(){ console.log('rend

我有一个名为
roles
的数组,我在其中循环并创建子组件。当我将一个项目推送到该数组时,所有子组件都在重新渲染(基于渲染方法中的
console.log

我认为react有智能虚拟dom diffing,其中只更新更改的项。那么,为什么所有的道具都会被重新渲染,甚至当一个额外的道具附加到数组中时,所有的子道具都保持不变呢?在错误地更新阵列的情况下,我是否做错了什么

var Child=React.createClass({
render:function(){
console.log('rendering!!')
return
  • {this.props.role.name}
  • ; } }); var Parent=React.createClass({ getInitialState:函数(){ 返回{ 角色:[ {name:'Admin',i:0}, {姓名:'看门人',i:1}, {姓名:'老师',i:2}, ] } }, addRole:function(){ var i=this.state.roles.length; var newRoles=this.state.roles.slice(); push({name:'some role',i:i}) 这是我的国家({ 角色:新角色 }) }, render:function(){ var roles=this.state.roles.map(函数(角色){ 返回 }); 返回(
      {角色} 添加角色
    ); } });
    默认情况下,React将始终重新渲染所有内容。有一个名为
    shouldComponentUpdate
    的生命周期方法可以启用此行为(它总是返回
    true

    通过使
    shouldComponentUpdate
    根据道具更改的内容返回true或false,您可以更改此选项,并告诉React不要一直重新渲染所有内容

    var Child = React.createClass({
        shouldComponentUpdate: function(nextProps) {
            if (this.props.role.name === nextProps.role.name) { 
                return false; 
            }
            return true;
        },
        render: function() {
            console.log('rendering!!')
            return <li>{this.props.role.name}</li>;
        }
    });
    
    var Child=React.createClass({
    shouldComponentUpdate:函数(下一步){
    如果(this.props.role.name==nextrops.role.name){
    返回false;
    }
    返回true;
    },
    render:function(){
    console.log('rendering!!')
    return
  • {this.props.role.name}
  • ; } });
    所以您应该始终尝试实现
    shouldComponentUpdate
    以获得更好的性能?如果您的计算非常昂贵,是的,否则不是。最后一个问题,如果我选择将
    name
    属性更改为其他属性,而不是按数组-为什么
    nextrops
    this.props在
    shouldComponentUpdate
    方法中相同?查看切片数组中的对象仍然是相同的对象,切片不会深度克隆或复制对象,它肯定会创建一个新数组,但会将对象保留在其中。
    var Child = React.createClass({
        shouldComponentUpdate: function(nextProps) {
            if (this.props.role.name === nextProps.role.name) { 
                return false; 
            }
            return true;
        },
        render: function() {
            console.log('rendering!!')
            return <li>{this.props.role.name}</li>;
        }
    });