如何在ajax调用响应后更新响应es6组件?
问题描述:
我是新来的反应和es6,并试图创建搜索字段,获取一些数据的类型,如果用户输入最少3个字符的字段它使Ajax调用使用抓取API,但我没有得到JSON数据,当我运行抓取代码段代码在浏览器控制台中显示json数据。我在我的代码中做了什么错误。如果我得到的数据,然后如何填充搜索列表我想知道什么是一旦收到数据更新组件的最佳方式。在下面的代码中,我创建了子组件,其中我有一个道具称为项目,我将通过状态更新道具是正确的方式来重新呈现反应组件?如何在ajax调用响应后更新响应es6组件?
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;
答
使用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;
});
};
目前我没有在上面的代码中传递用户类型值,但我也需要传递用户类型文本,所以我只需要在changeHandler方法中使用getLocationData?只是为了提问的目的,我使用json占位符api,但这将根据用户输入过滤数据 – nancy