【发布时间】:2020-09-03 20:36:17
【问题描述】:
我是 React 新手。
我需要在一个状态下更新对象的属性。 我尝试使用下面的代码并遇到错误。
你能解释一下我做错了什么吗?
export interface IResultSourcesListItemsState {
listitems: [
{
"Title": string,
"sourceGuid": string,
"isChecked": boolean
}
]
}
_
public constructor(props: IResultSourcesProps, state: IResultSourcesListItemsState) {
super(props);
this.state = {
listitems: [
{
"Title": "",
"sourceGuid": "",
"isChecked": true
}
],
};
ResultSources.siteUrl = this.props.webSiteUrl;
}
resultSourceValueChange(checked, value) {
let stateChanged = false;
const updatedState = this.state.listitems.map((listitem) => {
if (listitem.Title === "All" && listitem.isChecked) {
listitem.isChecked = false;
stateChanged = true;
}
return listitem;
});
if (stateChanged)
this.setState({listitems: updatedState});
}
我简化了我的代码, 现在这段代码可以工作了
const updatedState = this.state.listitems;
this.setState({listitems: updatedState});
但是这段代码没有编译,为什么?
const updatedState = [...this.state.listitems];
this.setState({listitems: updatedState});
【问题讨论】:
-
为什么需要
stateChanged变量? -
仅在发生更改时更新状态
-
能否添加完整代码。通常你可以使用
componentDidUpdate来做到这一点。这个的 Codesandbox 很有帮助。只需在此处添加最低限度的代码。如果我们有实时代码,它很容易调试 -
这是一个有很多依赖项的大项目。把它复制到操场上并不容易:(
-
能否包含定义 IResultSourcesListItemsState 的代码?
标签: reactjs typescript