React State 变量已定义,但它被视为未定义并在浏览器中收到错误

React State variable is defined but its taking as undefined and receiving the error in the browser

在 constructor 中的 this.state 行,我定义了 inStock 的值: false 。在 groupByCategory() 函数我有一个 if( this.state.inStock )。这导致未定义。但是如果我添加一个 'this.state?.inStock' 它就可以正常工作。只是想了解为什么即使我初始化了状态变量也会发生这种行为

const products = [
  { category: "Sporting Goods", price: ".99", stocked: true, name: "Football" },
  { category: "Sporting Goods", price: ".99", stocked: true, name: "Baseball" },
  { category: "Sporting Goods", price: ".99", stocked: false, name: "Basketball" },
  { category: "Electronics", price: ".99", stocked: true, name: "iPod Touch" },
  { category: "Electronics", price: "9.99", stocked: false, name: "iPhone 5" },
  { category: "Electronics", price: "9.99", stocked: true, name: "Nexus 7" }
];

type IProps = {

}

type IState = {
  query: string,
  inStock: boolean,
  group: {
    [name: string]: IProduct[]
  }
}
    class FilterableProductTable extends React.Component<IProps, IState> {
  constructor(props: IProps) {
    super(props)
    this.state = { query: '', inStock: false, group: this.groupByCategory(products) }
  }

  filterByName() {
    const filteredList = products.filter(each => {
      return each.name.startsWith(this.state.query)
    })
    this.groupByCategory(filteredList)
  }

  groupByCategory(list: IProduct[]) {
    let group = list.reduce((acc: any, next) => {
      const key = next.category
      if (!acc[key]) acc[key] = []
      if (this.state.inStock) { if (next.stocked) acc[key].push(next) }
      else acc[key].push(next)
      return acc
    }, {})
    this.setState({ group: group })
    return group
  }
}

状态变量初始化时this.state = {query: '', inStock: false, group: this.groupByCategory(products)}

groupByCategory() ,这个函数实际上使用状态变量 inStock 作为计算的需要。所以当初始化状态时,this.state 显然是未定义的,这就是错误的原因。

this.state 尚未分配给首次调用 groupByCategory 时。

这是因为您在 groupByCategory 内调用 您分配给 this.state

的初始值

在构造函数中完成这一行之前:

this.state = { query: '', inStock: false, group: this.groupByCategory(products) } 

JS 需要在 完成分配之前弄清楚对象的所有属性中的内容。

因此,它首先尝试通过调用 groupByProperties 来解析 group - 此时 this.state 尚未分配给

您可以通过像这样更改构造函数来解决此问题:

constructor (props: IProps) {
  super(props)
  this.state = { query: '', inStock: false }
  this.state.group = this.groupByCategory(products)
}

这样,this.state,更具体地说,this.state.inStock 在您调用 groupByCategory.

之前被分配