可能であればこの問題を見ることができるかどうかは、私は比較的新しいものです。私はクリックイベントでAPIにajax呼び出しを行い、結果を'SearchButtons'
コンポーネントの状態に格納しています。小道具として更新された状態を渡す
状態は、次に、小道具を介して子コンポーネントに渡されます。ただし、子コンポーネントの小道具(SearchForm
)は親コンポーネントの以前の状態と同じで、ユーザーがいずれかのボタンをクリックすると更新されません。
小道具が子コンポーネントに送信される前に、おそらくコンポーネントを更新する方法があるのでしょうか?
import React from 'react';
import SearchForm from './SearchForm'
class SearchButtons extends React.Component {
constructor(){
super();
this.state = {
data: {}
}
}
update(event){
$.ajax({
url: 'http://example/api/' + event.target.value,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({ data: data })
}.bind(this)
});
}
render() {
return (
<div>
<button type="button" value="people" onClick={this.update.bind(this)} className="btn btn-primary">People</button>
<button type="button" value="car" onClick={this.update.bind(this)} className="btn btn-primary">Car</button>
<button type="button" value="planet" onClick={this.update.bind(this)} className="btn btn-primary">Planet</button>
<SearchForm data={this.state.data} />
</div>
)
}
}
export default SearchButtons
import React from 'react';
class SearchForm extends React.Component {
componentWillReceiveProps(){
console.log(this.props.data);
}
render(){
return (
<form className="form-inline">
<div className="form-group">
<label className="sr-only" for="exampleInputEmail3"></label>
<input type="text" className="form-control" placeholder="Enter text..." />
</div>
<button type="submit" className="btn btn-default">Search</button>
</form>
)
}
}
export default SearchForm
何'SearchForm'はどのように見えますか? –
こんにちはJosh、上記のSearchFormのコードを追加しました。ありがとう。 – Bradley
ajax呼び出しから正しいデータが返されていますか? – azium