Ryu*_*ujo 0 javascript reactjs
我有updateLocation功能的目的是选择数值是否已存在于数组内部.如果它不存在,则此函数将值输入array然后将其打开state,反之亦然.
但是当我尝试点击它时,我收到了这样的错误:
未捕获的TypeError:无法读取未定义的属性"包含"
这是我写的代码:
updateLocation(e) {
let locationArray = this.state.checked.location;
let value = parseInt(e.target.value);
//v this is the error comes from v
if (locationArray.includes(value)) {
locationArray.splice(locationArray.indexOf(value), 1);
} else {
locationArray.push(value)
}
this.setState({
checked: {
location: locationArray
}
})
}
Run Code Online (Sandbox Code Playgroud)
我认为这个错误确实没有意义,因为以前有一个功能几乎相同,但它正常工作.
updateCategory(e) {
let categoryArray = this.state.checked.categories;
let value = parseInt(e.target.value);
//this one works fine even It looks the same like updateLocation()
if (categoryArray.includes(value)) {
categoryArray.splice(categoryArray.indexOf(value), 1);
} else {
categoryArray.push(value)
}
this.setState({
checked: {
categories: categoryArray
}
})
}
Run Code Online (Sandbox Code Playgroud)
国家
constructor(props) {
super(props);
this.state = {
jobs : [],
category: [],
location: [],
loading : true,
count : 8,
checked : {
categories: [],
location : []
}
}
}
Run Code Online (Sandbox Code Playgroud)
该updateCategory功能位于更新上方updateLocation
这updateLocation是调用的代码
<div className="card-body">
{state.location.map((item, i) => (
<div className="checkbox" key={i}>
<input type="checkbox" value={item.id} onChange={e => this.updateLocation(e)} checked={state.checked.categories.includes(item.id)}/> {item.city_name}
</div>
)}
<a onClick={e => this.viewAllLocation(e)} id="view-all-loc">View more >>></a>
<div id="show-loading-loc" style={{display: 'none'}}>Loading...</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我试图console.log(locationArray.includes(value))但奇怪的是没有出现错误,只是locationArray.includes(value)在控制台的结果是false
我找到了主要问题,updateLocation函数中的所有内容都能正常工作,但是当locationArray存储它时会出现错误state.但它仍然没有意义,因为我们已经checked.location处于状态
小智 5
问题在于,您在checked没有其他属性的情况下为对象分配了一个新实例.
this.setState({
checked: {
categories: categoryArray
}
})
Run Code Online (Sandbox Code Playgroud)
这setState是location从中删除属性this.state.checked.
你应该使用:
this.setState({
checked: {
...this.state.checked,
categories: categoryArray
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |