简体   繁体   English

反应 useState 不更新数组拼接

[英]React useState not updating on array splice

I have useState:我有使用状态:

const [localImportedCustomers, setLocalImportedCustomers] = useState([]);

and template, to show the data:和模板,以显示数据:

<tbody>
{
    localImportedCustomers.map((value, index) => {
        return (
            <tr key={index}>
                <td>{index+1}</td>
                {
                    value.map((value1, index1) => {
                        return (
                            <td key={index1}>{value1}</td>
                        )
                    })
                }
                <td>
                    <button 
                        className="c-btn c-btn-danger"
                        onClick={ (e) => { deleteRow(e, index) } }
                    >
                        <FaTrash />
                    </button>
                </td>
            </tr>
        )
    })
}
</tbody>

trying to delete specific row, by below function:试图通过以下 function 删除特定行:

const deleteRow = (e, index) => {
    e.preventDefault();
    let tmpArray = localImportedCustomers;
    tmpArray.splice(index, 1);
    setLocalImportedCustomers(tmpArray);
}

but template not updating, should someone has like this problem?但是模板没有更新,有人应该遇到这个问题吗? Thanks for answers before the time!感谢您在时间之前的回答!

you are referencing same array.您正在引用相同的数组。 try spreding it so it actully create new array in memory.尝试传播它,以便它实际上在 memory 中创建新数组。

    let tmpArray = [...localImportedCustomers];

splice() modifies the array in-place instead of creating a new array. splice()就地修改数组而不是创建新数组。 What this means is that you're setting state to the same array reference (even though its contents have changed), and React doesn't see that as an update to state.这意味着您将 state 设置为相同的数组引用(即使其内容已更改),并且 React 不会将其视为对 state 的更新。

Set state to a new array reference.将 state 设置为新的数组引用。 Which could be as simple as this:可以这么简单:

let tmpArray = [...localImportedCustomers];

This creates a new array and spreads the contents of the existing array into it.这将创建一个新数组并将现有数组的内容散布到其中。 So when state is updated, the array reference itself has changed and React sees it as new state.因此,当 state 更新时,数组引用本身发生了变化,React 将其视为新的 state。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM