Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ReactJs-i can';t捕获axios以外的变量';环_Javascript_Reactjs - Fatal编程技术网

Javascript ReactJs-i can';t捕获axios以外的变量';环

Javascript ReactJs-i can';t捕获axios以外的变量';环,javascript,reactjs,Javascript,Reactjs,我有一个JSON DB和一个React组件来获取这些数据。 这是我的JSON数据库: { "houses": [ { "id": 1, "name": "house 1" }, { "id": 2, "name": "house 2" }, { "id": 3, "name": "house 3" } ] } 它是由Rea

我有一个JSON DB和一个React组件来获取这些数据。 这是我的JSON数据库:

{
  "houses": [
    {
      "id": 1,
      "name": "house 1"       
    },
    {
      "id": 2,
      "name": "house 2"        
    },
    {
      "id": 3,
      "name": "house 3"
     }       
  ]
}
它是由ReactJS组件获取的。当我在Axios循环中执行console.log()时,它会成功工作。但在渲染方法内部,它不起作用。我怎样才能解决它

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
类包含扩展组件{
建造师(道具){
超级(道具);
此.state={
索引:0,
当前房屋:[]
};      
}
componentDidMount(){
axios.get(URL\u房屋)
.然后(res=>{
this.setState({index:0})
this.setState({currentHouse:res.data})
//开始工作了!它正在返回索引和当前房屋的名称
console.log('index:'+this.state.index)
console.log(
“当前房屋的名称:”+
this.state.currentHouse[this.state.index].name
) 
}
render(){
返回(
//此处不起作用。它正在返回错误消息:
//TypeError:无法读取未定义的属性“0”
{this.state.currentHouse[this.state.index].name}
);
}
}   
导出默认房屋

此错误的原因是
render()
方法试图在数据可用之前呈现数据。请尝试以下方法解决此问题:

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
类包含扩展组件{
建造师(道具){
超级(道具);
此.state={
索引:0,
当前房屋:[]
};      
}
componentDidMount(){
axios.get(URL\u房屋)
.然后(res=>{
/*合并为单个setState调用(这是可选的,但是
使代码更清晰。请注意,调用setState将
再次触发组件render(),这将导致
您的currentHouse[0]。要在下面呈现的名称*/
this.setState({index:0,currentHouse:res.data})
}
render(){
/*检测currentHouse数据是否准备就绪/可用-如果不可用,则渲染
临时加载消息*/
if(this.state.currentHouse.length==0){
返回加载

} /*如果我们到达这一点,那么在这个.state.currentHouse中就有数据 可以访问和呈现的*/ 返回( {this.state.currentHouse[this.state.index].name} ); } } 导出默认房屋
TL;DR在渲染方法中显示初始currentHouse数组之前,请先检查它。

在组件的初始渲染时,
currentHouse
数组中没有元素

因此,当您的组件试图打印语句
this.state.currentHouse[this.state.index].name
,它实际要做的是查找空数组的第0个位置
[]
。这将计算为
未定义的

解决此问题的一个选项是为状态中的currentHouse数组设置初始值,或者检查数组中是否有值。例如:

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