代码之家  ›  专栏  ›  技术社区  ›  Josh Simon

生命周期方法的混乱-为什么我的API调用不返回数据?

  •  0
  • Josh Simon  · 技术社区  · 6 年前

    我正在使用react建立一个酒吧网站,这要求我获取有关现成啤酒的信息。我正在从以下位置检索信息 http://www.hashigozake.co.nz/taplist.xml 如您所见,数据以XML格式返回。然后,使用名为xmlreactparser的库将此数据转换为js对象。

    无论如何,我已经编写了以下代码来进行这个API调用:

        componentDidMount() {
            const url = 'http://www.hashigozake.co.nz/taplist.xml'
            const proxyURL = 'https://cors-anywhere.herokuapp.com/'
          
            fetch(proxyURL + url)
            .then(res => res.text())
            .then(beerXML => {
              let beerJs = new XMLParser().parseFromString(beerXML)
              this.setState({
                beers: beerJs
              })
    
            })
          }
    

    问题就在这里。我正在传递曲目列表数据( {beerList =this.state.beers} )作为另一个名为 TileList.jsx 。在此组件中,我运行以下控制台日志: console.log(props.beerList.children[0]) 它应该返回一个对象数组,但实际上,它给了我一条错误消息,说 Uncaught TypeError: Cannot read property '0' of undefined .

    我怀疑正在发生的是,render()方法在fetch()方法完成返回数据之前被调用,这就是为什么我得到一个 undefined 当我尝试访问我的数据时。我很困惑,因为我认为componentDidMount是在render方法之后触发的,所以不应该渲染我的所有数据吗?

    不管怎样,下面更详细地看看我的代码:

    父组件: Home.jsx

    import React from 'react'
    import './styles.css'
    import hashi_logo_2 from './Photos/hashi_logo_2.png'
    import TileList from './TileList'
    import OnNextList from './OnNextList'
    import {Link} from 'react-router-dom'
    const XMLParser = require('react-xml-parser')
    
    class Home extends React.Component {
    
        constructor() {
            super()
            this.state = {
                beers:[]
            }
        }
    
        componentDidMount() {
            const url = 'http://www.hashigozake.co.nz/taplist.xml'
            const proxyURL = 'https://cors-anywhere.herokuapp.com/'
          
            fetch(proxyURL + url)
            .then(res => res.text())
            .then(beerXML => {
              let beerJs = new XMLParser().parseFromString(beerXML)
              this.setState({
                beers: beerJs
              })
    
            })
          }
    
        render() {
        return (
            <div className = 'home'>
                <nav className = 'nav'>
                    <ul>
                        <Link to = '/about' style={{ textDecoration: 'none' }} >
                            <li className='list'>About</li>
                        </Link>
                        <li className='list'>Food</li>
                        <li className='list'>Events</li>
                        <li className='list'>News</li>
                        <Link to ='/shop' style={{ textDecoration: 'none' }} >
                            <li className='list'>Shop</li>
                        </Link>
                        <li className='list'>Contact</li>
                        <li className='list'>Blog</li>
                    </ul>
                </nav>
                <main>
                    <div className='main__image'>
                        <img src= {hashi_logo_2}/>
                    </div>
                    <div>
                        <TileList beerList = {this.state.beers}/>
                        <OnNextList/>
                    </div>
                </main>
            </div>
        )
    }
    }
    
    export default Home
    

    子组件: TileList.jsx

    import React from 'react'
    import Tile from './Tile'
    
    const TileList = (props) => {
        console.log(props.beerList.children[0])
        return (
            <>
             <h1 className = 'h1-pouring'>Currently Pouring:</h1> 
            <div className = 'tile-container'>
                {
                    props.beerList.map(item => {
                        return <Tile 
                        />
                    })
                } 
            </div> 
            </>
        )
    }
    
    export default TileList
    

    此外,以下是作为道具发送的数据的(不完整)视图:

    {
      name: 'Products', attributes:{}, value:'', children: [
        {
          name:'Beers', attributes: {}, value: '', children: [
            {
              name: 'Product', attributes:{}, value:'', children: {
                
              }
            }
          ]
        }
      ]
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Drew Reese    6 年前

    问题

    您的初始状态没有提供足够的数据结构,无法更深入地正确访问。

    这个 beers 对象最初在中定义为空数组 Home

    this.state = {
      beers: [],
    }
    

    并作为道具传递给 TileList

    <TileList beerList={this.state.beers} /> // this.state.beers ~ []
    

    内 TileList 你试图立即更深入地记录

    console.log(props.beerList.children[0]);
    

    检查这一点, props.beerList 当前是空数组( [] )没有财产 children ,即。 props.beerList.children 或 props.beerList['children'] 未定义,因此尝试访问索引 0 将抛出错误 Uncaught TypeError: Cannot read property '0' of undefined .

    次要问题

    初始状态为 beers = [] ,但稍后响应形状是一个对象

    {
      name: 'Products', attributes:{}, value:'', children: [
        {
          name:'Beers', attributes: {}, value: '', children: [
            {
              name: 'Product', attributes:{}, value:'', children: {
                
              }
            }
          ]
        }
      ]
    }
    

    这种不一致的状态类型会使调试代码变得更加困难,或者换句话说,更容易产生有缺陷的代码。

    解决方案

    保持状态类型一致。

    this.state = {
      beers: {},
    }
    

    首先使用防护装置或可选的链条进行检查

    props.beerList.children &&
    props.beerList.children.length && 
    console.log(props.beerList.children[0]);
    

    或

    console.log(props.beerList?.children?.[0]);
    

    访问正确的嵌套属性以映射啤酒

    props.beerList.children &&
    props.beerList.children.length && 
    props.beerList.children[0].children && 
    props.beerList.children[0].children.map(product => ...
    
        2
  •  1
  •   Eric    6 年前

    根据反应文件 here ,setState是异步的,在第一次呈现中,props.beerList是一个空数组,然后setState()将触发第二次呈现,这样如果你的返回包含一个值,你就可以在第二次渲染中按索引获取值。

    setState()并不总是立即更新组件。也许吧 批处理或推迟更新。这使得阅读This。state 在调用setState()作为潜在陷阱之后。相反,使用 componentDidUpdate或setState回调(setState(updater, 回调),其中任何一个都保证在更新后触发 已应用。