私のプロジェクトでは、子SearchBarコンポーネントの入力を記入しています。子から親に状態を渡すと反応コンポーネントのライフサイクルが再開します
フォームを送信する際に、親コンポーネントのsearchQueryプロパティの状態を変更し、その状態をAPI呼び出しに使用したいとします。
親(App)コンポーネントから子(SearchBar)コンポーネントにhandleSubmit関数を渡し、入力値を関数に渡しました。次に、AppコンポーネントのhandleSubmit関数で、状態を必要な値に変更できます。
私はsetStateを使用して以来、これによってrender関数が再度実行され、続いてcomponentDidMountが実行されることが予想されました。
しかし、React Component Lifecycleが再開されたので、this.state.searchQueryは常に空の文字列の初期値にリセットされるため、空の文字列を常に検索します。
なぜReactコンポーネントライフサイクルのすべての機能が最初からやり直されていますか?私はこの問題を解決して、componentDidMountのapi呼び出しに適切な値を渡すことができますか?
私のコードは以下の通りです:コンポーネント(アプリケーション)
import React, { Component } from 'react';
import SearchBar from "./SearchBar.js"
class App extends Component {
constructor(props) {
super(props);
this.state = {
people: [],
planets: [],
searchQuery: ''
}
this.handleSubmit = this.handleSubmit.bind(this);
console.log('in constructor. this.state.searchQuery is: ', this.state.searchQuery) //empty string
}
handleSubmit(event, value) {
console.log('handle submit is called. value is: ', value);
this.setState({
searchQuery: value
},()=> {
console.log('this.state.searchQuery is:', this.state.searchQuery); //the value I type in
})
}
componentDidMount() {
console.log('this.state.searchQuery is: ', this.state.searchQuery) //empty string
//make api call
api.fetchPeople(this.state.searchQuery).then((results)=> {
//do stuff
}
}
render() {
console.log('in render. this.state.searchQuery is: ', this.state.searchQuery) //empty string
return (
<div className='content'>
<div className='logo'>
</div>
<SearchBar submit={this.handleSubmit} />
</div>
);
}
}
export default App;
子コンポーネント(検索バー)
import React, { Component } from 'react';
import './SearchBar.css';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
value: ''
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
value: event.target.value
})
}
handleSubmit(event) {
this.props.submit(event, this.state.value);
}
render() {
return (
<form onSubmit={this.handleSubmit} className='search-bar'>
<input onChange={this.handleChange} value={this.state.value} placeholder='Search Your Destiny' />
</form>
);
}
}
export default SearchBar;
私はcomponentDidUpdateの私の状態変化を見ることができます。しかしその後、コンポーネントライフサイクル全体が再び再開されます。私はenterを押して、私が防ぐ必要があるページのリフレッシュを引き起こすので、それが疑わしい。私はcomponentDidUpdateにevent.preventDefault()を配置しようとしましたが、そこにイベントを渡すことができず、正しいアイデアであるかどうかはわかりません。 – MattGoldwater
あなたはSearchBarコンポーネントのhandleSubmitでevent.preventDefault()を使用します。これにより、ページがリロードされなくなります。 –