首页 > 解决方案 > 对象中的访问状态

问题描述

我已经在我的状态下声明了一个对象,代码:

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'”这发生在用户对象中的所有属性中,即使它们在接口中声明。

标签: reactjstypescript

解决方案


当你这样做时,

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.statethis.setState

this.state = {
  attendtext: "Attend",
  showPanel: false,
  attendespanel: null,
  user: { isSiteAdmin: false }
};

现在您可以访问this.state.user.isSiteAdmin.


推荐阅读