【问题标题】:Reactjs - TypeError: Cannot read property 'map' of undefined (in funtional component)Reactjs - TypeError:无法读取未定义的属性“地图”(在功能组件中)
【发布时间】:2021-04-23 02:35:23
【问题描述】:

我正在做一个简单的反应应用程序,它可以从 API 调用中找到图像。但是有一个显示这个问题。 在 imageList.js 中我得到了这个错误。请帮我解决以下错误 TypeError: Cannot read property 'map' of undefined 我不知道如何解决我是新的反应 pease 帮我这个代码

App.js

import React from 'react';
import SearchBar from './SearchBar'
import unsplash from '../api/unsplash';
import ImageList from './imageList'

class App extends React.Component{
    state = {images : []}
   onSearchSubmit = async  (term) => {
       const response = await unsplash.get('/search/photos',{
            params : {query : term}
          })
        // .then ((response)=>{
            // console.log(response.data.results)

        // })
        this.setState({images : response.data.results});
            
        
    }
     
    render(){
       return(
           <div className='ui container' style={{marginTop : '10px'}}>
            <SearchBar onSubmit={this.onSearchSubmit} />
            <ImageList image = {this.state.images} />
        </div>
       );
    }
}
export default App;

搜索栏.js

import React from 'react';


class SearchBar extends React.Component{
   
    state = { term : ''}

    onSubmitForm = (event) => {
        event.preventDefault();
        this.props.onSubmit(this.state.term)
    }


    render(){
        return(
            <div className='ui segment'>
                <form onSubmit = {this.onSubmitForm} className = 'ui form'>
                    <div className= 'field'>
                        <label>Image Search</label>
                       <input type= 'text' 
                       value = {this.state.term}
                       onChange={(e)=>this.setState({term: e.target.value})} />
                    </div>
                </form>
            </div>
        )
    }
}

export default SearchBar;

imageList.js

import React from 'react';

const ImageList = (props)=>{
    
    const images = props.images.map(({description,id,urls})=>{
        return <img alt={description} key = {id} src= {urls.regular} /> ;
    });
    return(
        <div>{images}</div>
    )

};
export default ImageList

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您的道具被称为image,但在组件中,您通过props.images 访问它。将它们更改为相同。

    <ImageList image={this.state.images} />
    // Should be
    <ImageList images={this.state.images} />
    

    【讨论】:

      猜你喜欢
      • 2018-02-08
      • 2020-04-20
      • 2020-11-18
      • 2021-07-11
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多