我是 ReactJS 的初学者,我遇到了一个我不明白的错误。这是我第一个用 ReactJS 编写的应用程序。这是我的代码。
错误
react map 不是我应用中的函数错误
SearchBar 组件
import RecipeList from './recipes_list';
class SearchBar extends Component {
state = {
term : []
}
onInputChange(term){
this.setState({term});
}
onSubmit = async (term) => {
const recName= this.state.term;
term.preventDefault();
const api_key = 'a21e46c6ab81bccebfdfa66f0c4bf5e9';
const api_call = await Axios
.get(`https://www.food2fork.com/api/search?key=${api_key}&q=${recName}&`)
.then(res=> {this.setState({term : res.data.recipes})})
}
render() {
return (
<div>
<form onSubmit={this.onSubmit} >
<div className="search-bar">
<input
type="text"
value={this.state.term}
onChange={event => this.onInputChange(event.target.value)}
/>
<button type="submit">Search</button>
</div>
</form>
<RecipeList List ={this.state.term}/>
</div>
)
}
}
食谱列表组件
const RecipeList = props => (
<div>
{
props.List.map((recipe) => {
return (
<div>{recipe.title}</div>
)
})
}
</div>
)
export default RecipeList;
谢谢大家的帮助
最佳答案
您的问题出在这段代码中:
onInputChange(term){
this.setState({term});
}
这会将您的状态变量设置为字符串。例如,如果我输入 Hello!
,您的状态对象将是 { term: 'Hello!' }
。您现在正在尝试对字符串进行 .map()
,String.map
不是函数。
关于javascript - react map 不是我应用程序中的功能错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53519226/