reactjs - 对象中的访问状态
问题描述
我已经在我的状态下声明了一个对象,代码:
this.state = {
attendtext: "Attend",
showPanel: false,
attendespanel: null,
user: this.user
};
我用通常的 setState 更新它:
if (attenduser.isSiteAdmin) {
this.setState(prevState => ({
user: {
...prevState.user,
isSiteAdmin: true
}
}));
}
但我无法访问此对象属性。例如:
this.state.user.isSiteAdmin
以上无效。怎么来的?
我的界面:
export interface UserItem {
Key?: string;
Username?: string;
user?: {
title: string,
emailaddress: string,
isSiteAdmin: boolean
};
}
我还尝试使用以下方式设置状态:
this.state = {
attendtext: "Attend",
showPanel: false,
attendespanel: null,
user: { title: "", emailaddress: "", isSiteAdmin: false }
};
但是,它会变成红色“对象文字只能指定已知属性,并且在类型'UserItem []'中不存在'title'”这发生在用户对象中的所有属性中,即使它们在接口中声明。
解决方案
当你这样做时,
this.state = {
attendtext:"Attend",
showPanel: false,
attendespanel:null,
//
user: this.user
}
this.use
应该是您正在使用的组件的实例变量this.state
。
例如)
class App extends Component {
user: {}
constructor(props) {
super(props)
this.state = {...}
}
}
但是,每当App
组件重新渲染时,它就会this.user
被重置(回到初始的空对象,{}
),因为它不会由 React 管理。
所以更合适的声明状态的方法是将 包含在React 可以管理user
的部分中(CRUD with )this.state
this.setState
this.state = {
attendtext: "Attend",
showPanel: false,
attendespanel: null,
user: { isSiteAdmin: false }
};
现在您可以访问this.state.user.isSiteAdmin
.
推荐阅读
- ios - iOS - 独立于时区的本地通知
- python-2.7 - Pycharm 在控制台中运行代码时不显示局部变量
- azure - 我在使用 Azure 集成工具处理 XSLT 中的特定 EDI 856 HL 级别时遇到问题
- php - 使用 ffmpeg 将 mp4 转换为 x264 时数据无效,但将 flv 转换为 x264 时很好
- curl - 如何在 curl 中使用原始 YAML 文件来创建 Pod
- angular6 - 找不到管道“xxx”(
- visual-studio - 在 Visual Studio 2017 cmake 项目中指定命令行参数
- javascript - findOneAndUpdate mongodb 推送到现有数组
- python - 如何在 matplotlib 中包含另一个图形?
- listview - ListView 项目内的按钮 - 如何获取内容?