如何设置状态以从APi进行回答并使用地图

时间:2019-05-29 21:00:30

标签: reactjs setstate

我正在尝试创建食谱搜索器。在 App.js 中,我收到来自另一个组件的搜索输入的查询,我想setState来回答APi。 Console.log中的回调中的setState显示更新状态,但状态未更新。我需要更新setState,以便可以在上面使用map,并在render中显示配方列表。它给我错误映射不是函数,因为this.state.recipesList仍然为空。有人可以帮助我吗?

class App extends Component {
  state = {
    query: "",
    recipesList: []
  };

  getQuery = query => {
    const key = "2889f0d3f51281eea62fa6726e16991e";
    const URL = `https://www.food2fork.com/api/search?key=${key}&q=${query}`;

    fetch(URL)
      .then(res => res.json())
      .then(res => {
        this.setState(
          {
            recipesList: res
          },
          () => {
            console.log(this.state.recipesList);
          }
        );
      });
    console.log(this.state.recipesList);
  };
  render() {
     const test = this.state.recipesList.map(item => {
       return (
         <div className="recispesList">
           <h1>{item.title}</h1>
        </div>
       );
     });

    return (
      <div className="App">
        <Search query={this.getQuery} />
        <div className="contentWrapper">{}</div>
      </div>
    );
  }
}

搜索组件:

class Search extends Component {
  state = {
    searchValue: ""
  };

  handleChange = val => {
    let searchValue = val.target.value;
    this.setState({
      searchValue
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.setState({
      searchValue: ""
    });
    this.props.query(this.state.searchValue);
  };
  render() {
    return (
      <div className="searchWrapper">
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.handleChange} value={this.state.searchValue} />
          <button />
        </form>
      </div>
    );
  }
}

export default Search;

1 个答案:

答案 0 :(得分:1)

似乎不是直接将整个响应分配给recipesList

this.setState(
  {
    recipesList: res
  },
  () => {
    console.log(this.state.recipesList);
  }
);

您首先需要通过recipes获取res.recipes数组:

this.setState(
  {
    recipesList: res.recipes
  },
  () => {
    console.log(this.state.recipesList);
  }
);