首页 > 解决方案 > 无法读取未定义的长度属性

问题描述

我正在尝试将状态的长度呈现到屏幕上,它一直告诉我,无法读取未定义的长度属性。当我尝试将状态值记录到控制台时,起初它是未定义的,在运行搜索后更新值并且数组中有 5 个项目。现在的问题是当它更新时,它不会在屏幕上更新,或者它会完全崩溃。

export default class App extends Component {
    state={
       vidoes:[]
   };

    onTermSubmit = async term =>{
   const response = await youtube.get('/search',{
        params:{
            q:term,
        }
    });

    this.setState({videos:response.data.items})
   };



    render() {
        console.log(this.state.videos)
        return (
            <div className="ui container">
                <SearchBar onFormSubmit={this.onTermSubmit}/>
                {this.state.vidoes.length}
            </div>
        )
    }

最终目标是在屏幕上渲染状态的长度,现在它被描述为未定义,不可能循环遍历它。

标签: reactjs

解决方案


试试这个,

  export default class App extends Component {
            state={
               videos:[]
           };

            onTermSubmit = async term =>{
           const response = await youtube.get('/search',{
                params:{
                    q:term,
                }
            });

            this.setState({videos:response.data.items})
           };



            render() {
                console.log(this.state.videos)
                return (
                    <div className="ui container">
                        <SearchBar onFormSubmit={this.onTermSubmit}/>
                        {this.state.videos.length}
                    </div>
                )
            }

推荐阅读