【发布时间】:2019-08-30 16:32:51
【问题描述】:
我正在寻找一些反应项目示例,我在这里找到了一些 https://reactjs.org/community/examples.html
其中一个是购物车项目,我检查了代码,发现了一些我无法理解的东西,比较 componentWillReceiveProps 方法中的两个数组。
我知道比较两个数组总是会返回false,这是造成混乱的根源,在这里
https://github.com/jeffersonRibeiro/react-shopping-cart/blob/master/src/components/Shelf/index.js
我的问题在这部分
if (nextFilters !== this.props.filters) {
this.handleFetchProducts(nextFilters, undefined);
}
由于filters 是一个数组,如propTypes 所示。
一切都很好,这就是我提出这个问题的原因。
那么这里有什么问题,componentWillReceiveProps 是一种特殊方法,因此它至少可以在两个数组之间进行浅层比较,或者这里到底发生了什么???
【问题讨论】:
-
是的,您可以使用 === 运算符进行比较,根据 React 文档,componentWillReceiveProps() 是不安全的,请使用 componentDidUpdate() 或 getDerivedStateFromProps()
-
检查这里reactjs.org/docs/react-component.html#updating
componentWillReceiveProps是不安全的,应该避免使用 -
我试过这个 [1, 2, 3] === [1, 2, 3] 并且返回 false
标签: reactjs