“ TypeError:无法读取未定义的属性'名称'”错误

时间:2018-12-16 16:09:00

标签: javascript reactjs

代码给了我这个“ TypeError:无法读取未定义的属性'名称'”错误,尽管当我console.log时它给了我对象

import React from "react";

class Random extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      breweries: []
    };
  }

  componentDidMount() {
    fetch("https://api.openbrewerydb.org/breweries")
      .then(response => response.json())
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

  render() {
    const brewery = this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
    return(
      <div>{brewery.name}</div>
    )
  }
}

export default Random;

3 个答案:

答案 0 :(得分:2)

直到异步请求完成,

this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)] 

实际上将返回undefined,因为

Math.floor(Math.random()*this.state.breweries.length)

将返回0,并且由于this.state.breweries是一个空数组,因此它将返回undefined

({[][0]-> undefined)。


您必须确保brewery尚未定义的可能性,例如:

<div>{brewery && brewery.name}</div>

答案 1 :(得分:1)

有两种方法可以解决此问题。

方法1:UNSAFE_componentWillMount()

您可以使用UNSAFE_componentWillMount()代替componentDidMount()UNSAFE_componentWillMount()在呈现组件之前执行,因此您将在呈现内容之前将数据置于状态。这应该摆脱错误。

方法2:验证状态为!Empty

在您的render方法中,您可以添加一条if语句,如果状态中没有数据,则breweriesnull,否则Brewerys等于this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)]

类似的东西:

render() {
    const { breweries } = this.state;
    let brewery; 
    if (breweries.length === 0){
       brewery = null;
    } else {
      brewery= 
   this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
    }
    return(
      <div>{brewery.name}</div>
    )
  }

要获得额外的保险,可以将两种方法结合使用。如果这样做,您的组件将如下所示:

import React from "react";

class Random extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      breweries: []
    };
  }

  componentWillMount() {
    fetch("https://api.openbrewerydb.org/breweries")
      .then(response =>{ return response.json() })
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

  render() {
    const { breweries } = this.state;
        let brewery; 
        if (breweries.length === 0){
           brewery = null;
        } else {
          brewery= 
       this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
        }
    return(
      <div>{brewery.name}</div>
    )
  }
}

export default Random;

应该这样做。希望这会有所帮助。

编辑:警告

我写了willMount(),但是应该是UNSAFE_componentWillMount()。 componentWillMount()在版本17之后将无法使用。UNSAFE_componentWillMount()在版本17之后将无法使用。很抱歉。我忘了写不安全的东西。

答案 2 :(得分:0)

在尝试访问数组的索引之前,应确保已获取数据。当数组为空时,您的随机数学将得出0,结果为undefined

import React from "react";

class Random extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      breweries: null
    };
  }

  componentDidMount() {
    fetch("https://api.openbrewerydb.org/breweries")
      .then(response => response.json())
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

  render() {
    if (this.state.breweries) {
      const brewery = this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
      return(
        <div>{brewery.name}</div>
      )
    }

    return null
  }
}

export default Random;