gpt4 book ai didi

javascript - 未捕获的 TypeError : Cannot read property of null, 从数组 javascript 中删除元素

转载 作者:行者123 更新时间:2023-12-03 04:15:46 24 4
gpt4 key购买 nike

当调用删除按钮上的 onClick 时,我试图从数组中删除一个元素,当单击该按钮时,我收到 Uncaught TypeError: Cannot read property 'name' of null

为什么我会收到此错误?

removeData(key) {
console.log(key);
const data = this.state.data;
data[key] = null;
this.setState({ data });
}

renderData(key){
const user = this.props.data[key];
console.log(user.name);
console.log(user.id);
return(
<div key={key}>
<li> <strong> Name: </strong> {user.name},
<strong> ID: </strong> {user.id} </li>
<button onClick={() => this.props.removeData(key)}> Remove </button>
</div>
)
}

最佳答案

Why am I getting this error?

您明确将 data[key] 设置为 null:

data[key] = null;

当组件重新渲染时,它可能会使用“删除”的键调用 renderData (因为该属性仍然存在,其值只是 null)。 user 将为 null 并且访问 null.name 会引发错误。

<小时/>

根据您的实际需要,可以跳过 renderData 方法中的 null 值,或者实际上删除条目

delete data[key];

分配null不会删除属性:

var obj = {foo: 42};

// Doesn't actually remove the property
obj.foo = null;
console.log(obj);

// This removes the property
delete obj.foo;
console.log(obj);

I am trying to remove an element from an array

如果你真的有一个数组,那么还有更多的问题。 {...this.state.data} 不是克隆数组的合适方法,因为您最终得到一个对象

要在数组上正确执行此操作,您需要执行

removeData(key) {
// Assuming `key` is the index of the element
// Create copy
const data = Array.from(this.state.data);
// Remove element at index `key`
data.splice(key, 1);
this.setState({ data });
}

关于javascript - 未捕获的 TypeError : Cannot read property of null, 从数组 javascript 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44147518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com