Reactjs 当props具有函数或方法调用时,React shouldComponentUpdate返回true

Reactjs 当props具有函数或方法调用时,React shouldComponentUpdate返回true,reactjs,Reactjs,请帮助我理解为什么当我传递给它的道具有一个来自App.js的方法时,js会返回true,即使该方法根本没有改变 这是我的App.js return <Person name={cur.name} age={cur.age} job={cur.job} key={cur.id} change={(event) => this.changeName(event

请帮助我理解为什么当我传递给它的
道具有一个来自
App.js
的方法时,js
会返回
true
,即使该方法根本没有改变

这是我的
App.js

return <Person 
            name={cur.name} 
            age={cur.age} 
            job={cur.job} 
            key={cur.id} 
            change={(event) => this.changeName(event, cur.id)} 
            delete={(event) => this.deletePerson(cur.id)} 
        />;

按预期返回false,但控制台.log(nextrops.delete!==this.props.delete)会返回
console.log
始终返回true,即使我已删除了
App.js
deletePerson()
方法中的所有代码


为什么会这样?

当你传递一个像so
()=>someFunc()
这样的函数时,你实际上是在每个渲染上创建一个新函数。因此,虽然函数仍然做同样的事情,但在内存中它实际上是一个新函数

我建议您快速阅读这篇文章,以了解有关此问题的更多细节和一些解决方案

传递新函数的一种常见情况是,函数需要传递某种类型的参数,例如,一个id来知道要删除哪个项。一种常见的解决方案是将
id
作为支撑传递给组件和函数。看起来有点像这样

<Component 
  id={id}
  delete={deleteFunc}
/>

function Component(props) {

  const deleteItem() {
    props.delete(props.id);
  }

  return (
    <button onClick={deleteItem}>
      Delete
    </button>
  );
}

功能组件(道具){
常量deleteItem(){
删除道具(道具id);
}
返回(
删除
);
}

在这种情况下,函数将始终保持不变,我们仍然可以让函数接受它所需的参数。

当您说“删除了App.js deletePerson()方法中的所有代码”时,这是什么样子的?像这个deletePerson=(id)=>{}我想知道是否使用内联箭头函数(即
(事件)=>this.deletePerson(cur.id)
),每次都会创建一个新的函数对象吗?您是否尝试过将该函数赋给
render()
之外的变量?嗨,马特,请参阅Chaim Friedman的答案,也许它也会对您有所帮助。你是对的,在render()方法中使用arrow函数总是返回一个新函数objectIts,在我链接的文章中突出显示,但是我将更新我的答案,以包含这段信息,并提供一个示例。你为什么要检查
shouldComponentUpdate
中的
删除
属性?你能检查其他实际上影响组件渲染输出的道具吗?理想情况下,你并不想索引到你的道具来检查每个道具本身,因为这会导致比简单地检查旧道具是否与新道具作为一个整体相同更慢的检查。
console.log(nextProps.name !== this.props.name || nextProps.age !== this.props.age || nextProps.job !== this.props.job);
            console.log(nextProps.delete !== this.props.delete);
<Component 
  id={id}
  delete={deleteFunc}
/>

function Component(props) {

  const deleteItem() {
    props.delete(props.id);
  }

  return (
    <button onClick={deleteItem}>
      Delete
    </button>
  );
}