当 className 改变时,React children 重新渲染
React children re-render when className changed
当 className 更改或父更改时,React 子项重新呈现。
import React from 'react';
import { useSelector } from 'react-redux';
import items from './ItemsList.js';
import Item from './Item';
import './style.scss';
export default () => {
const isDisabled = useSelector((state) => state.Items.isDisabled);
return (
<div className={`container items-container col ${isDisabled ? 'disabled' : ''}`}>
<div className="row items">
{items.map((obj) => (
// All these items re-renders, when parent container className changed
<Item key={obj.id} obj={obj} />
))}
</div>
</div>
);
};
当 isDisabled
更改为 true
并且 disabled
样式附加到父 container
时,子 Item
元素重新呈现。
如何在不重新渲染子元素的情况下将 styles/classNames 附加到父元素?
<Items>
可以是纯成分
或
只需在 Items 中使用 shouldComponentUpdate() 生命周期挂钩。
对于你提到的是真实的,实际上只有一件事正在发生,那就是 isDisabled
是一个状态 属性 到那个父组件 .
并且由于您正在使用 Redux 并调用 useSelector((state)=>{})
,这实际上将 AppState 绑定到组件状态。因此,从概念上讲,通过使用 useSelector()
,您将 isDisabled
视为状态 属性。根据 React 的约定,任何状态更改的组件都必须 re-render。所以你的 parent
实际上是 re-rendering.
这里引用了 Hooks 文档中的重要引述:
The selector is approximately equivalent to the mapStateToProps
argument to connect conceptually
这里有一些参考资料可以帮助您更好地理解这个主题:
通过将 React.memo
添加到子项组件解决了我的问题。
当 className 更改或父更改时,React 子项重新呈现。
import React from 'react';
import { useSelector } from 'react-redux';
import items from './ItemsList.js';
import Item from './Item';
import './style.scss';
export default () => {
const isDisabled = useSelector((state) => state.Items.isDisabled);
return (
<div className={`container items-container col ${isDisabled ? 'disabled' : ''}`}>
<div className="row items">
{items.map((obj) => (
// All these items re-renders, when parent container className changed
<Item key={obj.id} obj={obj} />
))}
</div>
</div>
);
};
当 isDisabled
更改为 true
并且 disabled
样式附加到父 container
时,子 Item
元素重新呈现。
如何在不重新渲染子元素的情况下将 styles/classNames 附加到父元素?
<Items>
可以是纯成分
或
只需在 Items 中使用 shouldComponentUpdate() 生命周期挂钩。
对于你提到的是真实的,实际上只有一件事正在发生,那就是 isDisabled
是一个状态 属性 到那个父组件 .
并且由于您正在使用 Redux 并调用 useSelector((state)=>{})
,这实际上将 AppState 绑定到组件状态。因此,从概念上讲,通过使用 useSelector()
,您将 isDisabled
视为状态 属性。根据 React 的约定,任何状态更改的组件都必须 re-render。所以你的 parent
实际上是 re-rendering.
这里引用了 Hooks 文档中的重要引述:
The selector is approximately equivalent to the
mapStateToProps
argument to connect conceptually
这里有一些参考资料可以帮助您更好地理解这个主题:
通过将 React.memo
添加到子项组件解决了我的问题。