簡體   English   中英

我想要 React js 中 ComponentDidMount 和 ComponentDidUpdate 的組合功能

[英]I want the combined functioanlity of ComponentDidMount and ComponentDidUpdate in React js

我正在使用 axios 獲取 API 數據,並且 API 具有查詢參數(例如:searchQuery,在狀態中定義)。 我已經在 state 和 axios 調用 componentDidUpdate 中聲明了它的初始值。 現在我希望我的用戶以提交時將在 state 中更改“seachQuery”的形式輸入數據。問題來了,我想根據用戶的輸入顯示具有提供的值和未來結果的初始結果,但它沒有發生。 初始結果沒有顯示,因為 componentDidUpdate 只會在更新后調用。 如果我在 componentDidMount 中進行了 axios 調用,則不會顯示根據用戶輸入的結果。 我只想使用基於 CLASS 的組件來做這件事。

  constructor(props) {
    super(props)
  
    this.state = {
      searchResult: [],
      formInput: "",
      searchQuery: "chicken",
    }
  }
componentDidUpdate(){
    axios.get(`https://api.edamam.com/search? 
       q=${this.state.searchQuery}&app_id=${this.state.APP_ID}&app_key=${this.state.APP_KEY}`)
            .then(res=>  
              this.setState(prevState =>({searchResult: prevState.searchResult.concat(res.data.hits)}))
              )
  }

onChangeHandler = (e) => {
    this.setState({
      formInput: e.target.value
    })
    console.log(e.target.value)



  }

  onSubmitHandler = (e) => {
    e.preventDefault()
    this.setState({
      searchQuery: this.state.formInput
    })
    // console.log(this.state.searchQuery)
    
    // setformInput("")
  }
  render() {
    return (
      <div className="App">
        <form className="search-form" onSubmit={this.onSubmitHandler}>
          <input className="search-bar" type="text" onChange={this.onChangeHandler} />
          <button className="search-button" type="submit">SEARCH</button>
        </form>
        <div className="recipes">
          {this.state.searchResult.map(singleRecipe => 
                          <Recipe key={singleRecipe.recipe.label} title={singleRecipe.recipe.label} calories={singleRecipe.recipe.calories} image={singleRecipe.recipe.image} ingredients={singleRecipe.recipe.ingredients}/>
          )}
        </div>
      </div>
    );
  }
}


export default App```

我認為您可以在 componentDidMount 中設置狀態(例如 searchQuery)。

componentDidMount() {
    this.setState({searchQuery: 'checken'});
}

為什么將 formInput 設置為用戶輸入並將 searchQuery 設置為 formInput onSubmit? 只需將 searchQuery 設置為用戶輸入 onChange。

onChangeHandler = (e) => {
  this.setState({
    searchQuery: e.target.value
  });
  console.log(e.target.value);
}

並在 function 中獲取數據,在 componentDidMount 和 onSubmit 上使用它。

getData = () => {
  axios.get(`https://api.edamam.com/search? q=${this.state.searchQuery}&app_id=${this.state.APP_ID}&app_key=${this.state.APP_KEY}`)
    .then(res =>
      this.setState(prevState => ({ searchResult: prevState.searchResult.concat(res.data.hits) }))
    );
}

componentDidMount() {
  this.getData();
}

onSubmitHandler = (e) => {
  e.preventDefault();
  this.getData();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM