React.useMemo 不更新数据 [英] React.useMemo does not update the data

查看:17
本文介绍了React.useMemo 不更新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是钩子的新手.所以这可能很容易,但我不知道如何解决:

I am new to hooks. So this might be easy yet I have no idea how to solve:

我有一个这样的函数,它需要两个数组 columnsdata .并且这些数据应该被记住,否则它不起作用.(由 react-table 人员推荐)

I have a function like this which takes two arrays columns and data . and those data should be memoized or else it does not work. (recommended by react-table guys)

function ReactTable(props) {

    const columns = React.useMemo(() => props.columns, [])

    const data = React.useMemo(() => props.data, [])

    return <Table columns={columns} data={data} />
}

这工作正常,但是当 props 改变时(比如从数据数组中添加或删除一个项目),React.useMemo 不会将更新的数据发送到 Table 组件.我该如何解决这个问题:(

this works fine but when the props change (say an item is added or removed from data array), the React.useMemo won't send the updated data to the Table component. How can I resolve this :(

推荐答案

这正是 hooks 中的依赖数组的用途.您可以定义触发"挂钩更改的变量.在您的情况下,这意味着您需要将代码更改为以下内容:

This is exactly what the dependency array in hooks is for. You can define variables that 'trigger' the change on hooks. In your case this would mean that you would need to change your code to the following:

function ReactTable(props) {
    const columns = React.useMemo(() => props.columns, [props.columns]);
    const data = React.useMemo(() => props.data, [props.data]);

    return <Table columns={columns} data={data} />
}

这意味着,每当 props.columns 更改时,columns 变量都会更新,对于 props.datadata 也是如此.

This means, whenever props.columns changes, the columns variable is updated and the same for props.data and data.

这篇关于React.useMemo 不更新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆