React中从App.js传列表到组件报错:List.map()不是函数
解决React中“List.map() is not a function!”报错问题
错误根源
在GoogleSuggestions组件的state初始化代码中,你错误地将整个props对象赋值给了state.suggestionsList:
state = {suggestionsList: this.props, searchInput: ''}
this.props是包含所有传入属性的对象(结构为{suggestionsList: [...]}),而非你需要的数组,所以调用map方法时会触发报错。
修复步骤
1. 修正state初始化逻辑
将state中的suggestionsList改为从props中提取对应数组:
state = {suggestionsList: this.props.suggestionsList, searchInput: ''}
2. 修正输入事件绑定
原代码中input使用onClick事件,仅在点击输入框时触发,无法响应输入内容变化。需要替换为onChange事件:
<input type="search" value={searchInput} onChange={this.showoptions} // 替换onClick为onChange className="input" placeholder="Search Google" />
3. 可选:添加搜索过滤逻辑(实现动态筛选建议)
如果需要根据输入内容实时过滤建议列表,修改render方法中的列表处理逻辑:
const filteredSuggestions = suggestionsList.filter(item => item.suggestion.toLowerCase().includes(searchInput.toLowerCase()) ) // 渲染时使用过滤后的列表 <ul className="ul-cont"> {filteredSuggestions.map(eachItem => ( <SuggestionItem itemDetails={eachItem} key={eachItem.id} /> ))} </ul>
修复后的完整GoogleSuggestions组件代码
import {Component} from 'react' import SuggestionItem from '../SuggestionItem' import './index.css' class GoogleSuggestions extends Component { state = {suggestionsList: this.props.suggestionsList, searchInput: ''} showoptions = event => { this.setState({searchInput: event.target.value}) } render() { const {suggestionsList, searchInput} = this.state const filteredSuggestions = suggestionsList.filter(item => item.suggestion.toLowerCase().includes(searchInput.toLowerCase()) ) return ( <div className="bg-container"> <img className="googleLogo" src="https://assets.ccbp.in/frontend/react-js/google-logo.png" alt="google logo" /> <div className="input-container"> <div> <img className="search-icon" src="https://assets.ccbp.in/frontend/react-js/google-search-icon.png" alt="search icon" /> <input type="search" value={searchInput} onChange={this.showoptions} className="input" placeholder="Search Google" /> </div> <ul className="ul-cont"> {filteredSuggestions.map(eachItem => ( <SuggestionItem itemDetails={eachItem} key={eachItem.id} /> ))} </ul> </div> </div> ) } } export default GoogleSuggestions
内容的提问来源于stack exchange,提问作者Tejaswi Kurapati
相关产品推荐
相关产品推荐

