在此之后未重置的形式 - setstate-反应



试图重置搜索输入字段,但setState无法正常工作

我尝试了几个堆栈溢出响应,但我敢肯定我缺少一些很小的东西。只是不确定什么

我有一个状态:searchInput属于app.js,我将其传递到搜索字段中,如下:

searchInputcomponent.js

// the Search and SearchInput are styled components so basically div and an input
  <Search>
    <SearchInput
      type="text"
      onChange={this.props.updateSearch}
      name="searchInput"
      value={this.props.searchInput}
      placeholder="Search for a food..."
    />
    <SearchButton onClick={this.props.getFoodData}>Search</SearchButton>
  </Search>

我知道搜索输入正在通过,因为我能够在现场看到类型的项目。

我有一个称为getfooddata的函数,该函数搜索有关搜索input的API,我能够获得结果

app.js- searchInput状态在这里生活,在输入字段上键入

时已更改
updateSearch = e => {
 this.setState({
   [e.target.name]: e.target.value
 });
};
//Code to check the API:  
getFoodData = food => {
food = this.state.searchInput;
let encodedFood = food.replace(" ", "%20");
this.setState({ showModal: true});
axios
  .get(
    `https://api.edamam.com/api/food-database/parser?ingr=${encodedFood}&app_id=${EDAMAM_API_ID}&app_key=${EDAMAM_API_KEY}`
  )
  .then(response => {
    console.log('pre-reset', this.state.searchInput);
    this.setState({
      searchResults: response.data.hints,
      searchInput: "",
      noResultError: "",
      resultsLoading: false
    });
    console.log("search results", this.state.searchResults);
    console.log("search input", this.state.searchInput);
  })
  .catch(error => {
    this.setState({
      searchInput: "",
      noResultError: "No results found",
      showModal: true,
      searchResults: []
    });
    console.log("error", error);
  });

};

然后将这些功能传递到JSX

中的SearchInputComponent中
        <SearchInputComponent
        updateSearch={this.props.updateSearch}
        searchInput={this.props.searchInput}
        getFoodData={this.props.getFoodData}
      />

我是否错过了为什么这没有清除搜索字段的原因,即使响应后我的搜索键是重置的?我可以在重置之前和重置和SearchInput清除后在控制台中看到它。

我希望搜索字段能与原始占位持有人一起清除甚至一个空字段。

如果我正确理解这一点,则应在SearchInputComponent中使用componentWillReceiveProps在Props更改时更新SearchInputComponent状态。在SearchInputComponent中,当最初设置状态时,将状态值设置为Prop值,this.state = { searchInput: this.props.searchInput }并使用this.state.searchInput进行字段值。

最新更新