我是新手反应和es6并尝试创建搜索字段,如果用户在字段上键入最少3个字符,则使用fetch api进行ajax调用,但是我在运行fetch snippet时没有获取json数据浏览器控制台中的代码显示json数据。什么是错的我在我的代码中做。如果我获取数据然后如何填充搜索列表我想知道一旦接收到数据更新组件的最佳方法是什么。在下面的代码中,我创建了子组件,其中我有一个名为items的prop我将通过状态更新prop这是重新渲染react组件的正确方法吗?
import React from 'react';
import SearchList from "./searchlist"
class SearchField extends React.Component {
constructor(props) {
super(props);
this.state = {SearchText:null,SearchData:{},KeyState:false, items:[]};
};
GetLocationData(){
fetch("http://jsonplaceholder.typicode.com/albums")
.then( (response) => {
return response.json() })
.then((json) => {
return json;
});
};
ChangeHandler(e){
e.preventDefault();
let isKeyUp = this.state.KeyState,
SearchFieldLength = e.target.value,
KeyLength = this.props.KeyRefresh;
if(!isKeyUp && SearchFieldLength.length > KeyLength){
let jsonData = this.GetLocationData();
//this.setState({SearchData:jsonData,KeyState:true})
console.log(jsonData);
}
};
componentDidMount(){
};
render() {
let PlaceholderText = this.props.PlaceHolderText;
return (
<div className="input-text-area">
<input type="text" placeholder={PlaceholderText} onChange={this.ChangeHandler.bind(this)} />
<SearchList items={this.state.items} />
</div>
);
}
}
export default SearchField;
答案 0 :(得分:0)
使用componentDidMount
componentDidMount {
this.GetLocationData();
}
您应该使用compnentDidMount
并从那里拨打GetLocationData()
。您需要在state
方法中更新GetLocationData()
,然后系统会自动为您调用渲染方法。
GetLocationData(){
fetch("http://jsonplaceholder.typicode.com/albums")
.then( (response) => {
return response.json() })
.then((json) => {
this.setState({
items: json
})
return json;
});
};