首页 > 解决方案 > 反应地图不是我的应用程序中的功能错误

问题描述

我是 ReactJS 的初学者,我遇到了一个我不明白的错误。这是我第一次使用 ReactJS 编写的应用程序。这是我的代码。

错误

react map is not a function error in my app

搜索栏组件

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;

谢谢你们的帮助

标签: javascriptreactjs

解决方案


您的问题在此代码段中:

onInputChange(term){
 this.setState({term});
}

这会将您的状态变量设置为字符串。例如,如果我输入Hello!,您的状态对象将是{ term: 'Hello!' }。你现在试图.map()通过一个字符串,String.map不是一个函数。


推荐阅读