每当存储中的未连接状态发生变化时,React redux组件都会重新应答.我该如何预防



我有一个名为FileHeader的组件。每次我调整其中一列的大小时,它都会分派一个操作来更改状态。这会触发重新应答。

ListeHeader.js

const ListHeader = props => {
const dispatch = useDispatch()
let headerRef = useRef(new Array())
const { header_ } = useSelector((state) => state.ui, shallowEqual)

const onResize = ( e, {event, node, size}) => {

dispatch(changeHeaderWidth(node.id, size.width))
}

return (
<HeaderBody>
{header_

.map((header) => {
const getRef = (element) => headerRef.current.push(element)
return (
<ResizableBox
axis="x"
width={header.width}
height={20}
key={header.id}
handle={<DragHandle id={header.id} />}
onResize={onResize}
minConstraints={[50, 20]}
maxConstraints={[300, 20]}
>
<Header
key={header.id}
width={header.width}
handleDrag={handleDrag}
onClick={handleSort(header.id)}
>
<HeaderText ref={getRef}>{header.name}</HeaderText>
</Header>
</ResizableBox>
)
})}
</HeaderBody>
) 
}

这是我的减速器

export default (state = initial_state, actions) => {
switch (actions.type) {
case consts.CHANGE_HEADER_WIDTH :  return {
...state,
headerWidth: state.headerWidth.map((item) =>
item.id === actions.payload.id ?  { ...item, width: actions.payload.neWidth} 
: item),
} 

break;

default: return state;
}
}

我没有在我的组件中调用headerWidth状态,当它更改时会导致重新应答

从文档

当使用分派将回调传递给子组件时,您可以有时想用useCallback来记忆它。如果子组件正在尝试使用React.memo((或类似方法优化渲染行为,这避免了由于更改了回调引用。

import React, { useCallback } from 'react'
import { useDispatch } from 'react-redux'
export const CounterComponent = ({ value }) => {
const dispatch = useDispatch()
const incrementCounter = useCallback(
() => dispatch({ type: 'increment-counter' }),
[dispatch]
)
return (
<div>
<span>{value}</span>
<MyIncrementButton onIncrement={incrementCounter} />
</div>
)
}
export const MyIncrementButton = React.memo(({ onIncrement }) => (
<button onClick={onIncrement}>Increment counter</button>
))

最新更新