javascript - 我使用 React hooks 和 React memo 来防止我的功能组件重新渲染,但不起作用?
问题描述
我使用 React.memo 来控制重新渲染,但我的组件仍然重新渲染。我的代码是这样的:
在我的模板组件中:
const Template = (props: Props) => {
const { propsValue, data } = props
const [value, setValue] = useState(propsValue)
const handleChange = (value) => {
setValue(value)
props.onChange(value)
}
return (
<div>
{info.type === 'input' && <Input value={value} onChange={(event, val) => handleChange(val) onBlur={(event) => handleBlur()} />
{info.type === 'image' && <Uploader multiple value={value} uploadUrl={data.uploadUrl} onChange={(val) => handleChange(val)} />
{info.type === 'select' && <Select onChange={(val) => handleChange(val)} />
</div>
)
}
const areEqual = (prevProps, nextProps) => {
if (JSON.stringify(prevProps) !== JSON.stringify(nextProps)) {
return false
}
return true
}
export default React.memo(EditTemplate, areEqual)
在我的上传器组件中:
const Uploader = props => {
const [value, setValue] = useState(props.value)
let { uploadUrl, multiple } = props
const handleChange = ({ file, fileList }) => {
if (file.status === 'done') {
setValue(fileList)
props.onChange(fileList)
} else {
setValue(fileList)
}
}
return (
<div>
<Upload fileList={value} multiple={multiple} action={uploadUrl} onChange={handleChange} />
</div>
)
}
const areEqual = (prevProps, nextProps) => {
if (JSON.stringify(prevProps) !== JSON.stringify(nextProps)) {
return false
}
return true
}
export default React.memo(Uploader, areEqual)
当我在选择组件中更改值时,areEqual 似乎不起作用,上传组件中所有图像的地址将重新加载。为什么...?
像这样的表现:
我能怎么做?
解决方案
重新渲染可能是由于内部状态更改(setValue(value)
)。React.memo
不会阻止由状态更改引起的重新渲染。
React.memo 仅检查 prop 更改。如果你封装在 React.memo 中的函数组件在其实现中有一个 useState 或 useContext Hook,它仍然会在状态或上下文发生变化时重新渲染。
推荐阅读
- docker - 如何恢复 docker 容器数据
- php - 在 AWS S3 中将多个文件从一个存储桶复制到另一个存储桶的最佳方法是什么?
- azure - 如何在 Azure 中获取多会话 VM 的用户级 CPU 利用率
- python - 将文本文件转换为十六进制 - 换行问题
- ssis - 一次处理多个 SSAS 多维数据集
- python - 将命令行命令转换为通常的 python 字符串
- reactjs - 在反应中克隆 github 项目
- javascript - 如何为多次使用相同钩子的屏幕创建测试?反应测试库
- javascript - 错误:用于查看 PDF 的角度项目中的对象可能为“空”
- ssl - 看不到来自 Charles 的移动应用请求