首页 > 解决方案 > TypeError:无法读取未定义的属性“groupsUrl”

问题描述

试图让我的状态每 5 秒从我的 db api 更新一次,但我收到一个错误,即即使它是状态也没有定义。

我知道 setState 是异步的,但是在 componentDidMount 中它可以读取状态,因此按照我的逻辑,如果 componentDidMount 调用 reSetStates 它肯定能够读取状态。

class Groups extends Component {
  state = {
    groups : {},
    categories : ["id", "name", "last fault", "active"],
    groupsInfoList : [],
    enabledGroupsInfoList : [],
    disabledGroupsInfoList : [],
    groupsUrl : 'http://my.api.server/groups'
  }

  componentDidMount() {
    fetch(this.state.groupsUrl)
    .then(res => res.json())
    .then((data) => {
      var groups_object = data['result']
      this.setStates(groups_object)
      this.reSetStates()
    })
    .catch(console.log)
  }

  reSetStates(){
    fetch(this.state.groupsUrl)
    .then(res => res.json())
    .then((data) => {
      var groups_object = data['result']
      this.setStates(groups_object)
    })

    .catch(console.log)

    setTimeout(this.reSetStates, 3000);
  }

标签: javascriptreactjs

解决方案


这是绑定问题,改变这个

reSetStates(){

至:

reSetStates = () => {

推荐阅读