简体   繁体   English

ReactJs - 我无法在 axios 循环之外捕获变量

[英]ReactJs - i can't catch a variable outside of the axios' loop

I Have a JSON DB and a React Component that fetch these datas.我有一个 JSON DB 和一个 React 组件来获取这些数据。 Here is my JSON DB:这是我的 JSON 数据库:

{
  "houses": [
    {
      "id": 1,
      "name": "house 1"       
    },
    {
      "id": 2,
      "name": "house 2"        
    },
    {
      "id": 3,
      "name": "house 3"
     }       
  ]
}

It is fetching by a ReactJS Component.它由 ReactJS 组件获取。 When I do console.log() inside of a Axios' loop it works successfully.当我在 Axios 循环中执行 console.log() 时,它会成功运行。 But inside of the render method it isn't working.但是在渲染方法内部它不起作用。 How can I solve it?我该如何解决?

class Houses extends Component {
  constructor(props) {
    super(props);
    this.state = {
      index:0,         
      currentHouse:[]      
    };      
  }

  componentDidMount() { 
    axios.get(URL_HOUSES)
      .then(res => {        
        this.setState({ index:0 })
        this.setState({ currentHouse: res.data})          
        //Here is working! It is returning the index and the current house's name      
        console.log('index:' + this.state.index)             
        console.log(
                     'Name of the current house:' +  
                      this.state.currentHouse[this.state.index].name
                    ) 
    }

  render() {                  

    return (
      <div>     
        //Here isn't working. It is returning an error message:  
        //TypeError: Cannot read property '0' of undefined

        <h3>{this.state.currentHouse[this.state.index].name}</h3>
      </div>
    );
  }
}   


export default Houses

TL;DR check initial currentHouse array before displaying it in the render method. TL;DR 在渲染方法中显示它之前检查初始 currentHouse 数组。

On the initial render of your component, there are no elements in the currentHouse array.在组件的初始渲染中, currentHouse数组中没有元素。

So when your component tried to print out your statement this.state.currentHouse[this.state.index].name , what it's actually trying to do is find the 0th position of an empty array [] .因此,当您的组件试图打印出您的语句this.state.currentHouse[this.state.index].name ,它实际要做的是找到空数组[]的第 0 个位置。 This will evaluate to undefined .这将评估为undefined

An option to fix this is set an initial value to the currentHouse array in the state, or check to see if there are values in the array.解决此问题的一个选项是为 state 中的 currentHouse 数组设置初始值,或者检查数组中是否有值。 For example:例如:

 <h3>{this.state.currentHouse.length && this.state.currentHouse[this.state.index].name}</h3>

The reason for this error is that the render() method is trying to render data before that data is available.此错误的原因是render()方法试图在数据可用之前呈现数据。 Try the following to resolve this issue:请尝试以下操作来解决此问题:

class Houses extends Component {
  constructor(props) {
    super(props);
    this.state = {
      index:0,         
      currentHouse:[]      
    };      
  }

  componentDidMount() { 
    axios.get(URL_HOUSES)
      .then(res => {        
        /* Combine into single setState call (this is optional, but 
           makes for cleaner code. Note that calling setState will
           trigger the component to render() again, which will cause
           your currentHouse[0].name to be rendered into <h3> below  */
        this.setState({ index:0, currentHouse: res.data })
    }

  render() {                  

    /* Detect if currentHouse data is ready/avalible - if not, render
       a temporary loading message */
    if(this.state.currentHouse.length === 0) {
       return <p>Loading</p>
    } 

    /* If we reach this point, then there is data in this.state.currentHouse
       that can be accessed and rendered */
    return (
      <div>         
        <h3>{this.state.currentHouse[this.state.index].name}</h3>
      </div>
    );
  }
}   


export default Houses

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM