***此组件进行REST API调用并解析promise值并以表的形式呈现数据。 load(function)进行API调用并将orderType作为输入。 OrderType作为查询参数从导航组件传递,此参数未包含在此处。
class SampleController extends React.Component {
constructor(props){
super(props);
let orderType = this.props.location.query.orderType;
this.load = this.load.bind(this);
this.load(orderType);
this.state = {orderType: orderType, data: null}
}
load(orderType) {
let self = this;
console.log("order type is" + orderType);
let baseURL = base_urls.orderMetricsBaseURL;
console.log("base URL is", baseURL);
let url = baseURL + "/getData";
let response_data = fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
order_type: orderType
})
})
.then((response) => response.json())
.then((responseJson) => {
let order_data = responseJson;
console.log("responseeeeee is: ", order_data);
self.setState({data: order_data});
self.forceUpdate();
})
.catch((error) => {
console.error(error);
});
}
render() {
var content = <DataTable dataList = {this.state.data} />;
return (
content
);
}
}
export { SampleController as default };
答案 0 :(得分:0)
setState()
不会立即更新状态,因此您可能因forceUpdate()
而失去该更新,因为setState()
会触发重新启动自己渲染。尝试删除forceUpdate()
来电。
更新
如果您想在load()
每次需要订阅componentWillReceiveProps方法时调用orderType
方法。
示例:
class SampleController extends React.Component {
constructor(props){
super(props);
let orderType = this.props.location.query.orderType;
this.load = this.load.bind(this);
this.load(orderType);
this.state = {orderType: orderType, data: null}
}
componentWillReceiveProps(nextProps) {
const orderType = nextProps.location.query.orderType;
const prevOrderType = this.props.location.query.orderType;
if (prevOrderType !== orderType) {
this.load(orderType);
}
}
load(orderType) {
let self = this;
console.log("order type is" + orderType);
let baseURL = base_urls.orderMetricsBaseURL;
console.log("base URL is", baseURL);
let url = baseURL + "/getData";
let response_data = fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
order_type: orderType
})
})
.then((response) => response.json())
.then((responseJson) => {
let order_data = responseJson;
console.log("responseeeeee is: ", order_data);
self.setState({data: order_data});
})
.catch((error) => {
console.error(error);
});
}
render() {
var content = <DataTable dataList = {this.state.data} />;
return (
content
);
}
}
export { SampleController as default };
答案 1 :(得分:0)
从构造函数中删除此行this.load(orderType);
并将其放在componentDidMount
:
constructor(){
//....
}
componentDidMount() {
const orderType = this.props.location.query.orderType;
this.load(orderType);
}
答案 2 :(得分:0)
您需要setState
触发重新运行/重新渲染组件。