【发布时间】:2021-12-24 09:35:14
【问题描述】:
需要把这个类组件代码改成功能组件,把这个类组件转成功能组件需要做哪些改动。请检查代码以了解更改。我更喜欢使用功能组件,所以我希望将此代码转换为功能组件
class MTS extends React.Component {
constructor(props) {
super(props);
this.state = {
message:null,
msgStatus: null,
version :null ,
data: [],
clusters:null
};
this.receiveData = this.receiveData.bind(this);
}
//************************************************************************
onGetAPI=()=>{
var _self = this;
fetch('http://127.0.0.1/api/v1/version')
.then(response =>
{
this.setState({ msgStatus : response.status, strStatusText : response.statusText }) // console.log(this.msgStatus) ;
return response.json();
})
.then(data => this.setState({ version : data }))
.then(function(json) {
console.log(json);
_self.receiveData(json);
});
}
//*************************************************************************
onGetClusters=()=>{
<label>Cluster ID <input style={{backgroundColor: "lightgray"}} type = "textarea" ref ="input"></input></label>
var _self = this;
fetch('http://127.0.0.1/api/v1/clusters')
.then(response =>
{
this.setState({ msgStatus : response.status , strStatusText : response.statusText}) // console.log(this.msgStatus) ;
return response.json();
})
//.then(data => this.setState({ clusters : data })
.then(function(json) {
console.log(json);
_self.receiveData(json);
} );
}
//*************************************************************************
receiveData(data) {
this.setState({data});
}
//*************************************************************************
onGetClustersID=()=>{
var _self1 = this;
let clusterinfo = this.refs.input.value;
//let clusterinfo1 =JSON.parse(clusterinfo);
console.log(clusterinfo);
fetch(' http://127.0.0.1/api/v1/clusters/'+ clusterinfo)
.then(response =>
{
this.setState({ msgStatus : response.status, strStatusText : response.statusText }) // console.log(this.msgStatus) ;
return response.json();
})
//.then(data => this.setState({ clusters : data })
.then(function(json) {
console.log(json);
_self1.receiveData(json);
} );
}
render(){
return(
<h4>Response status : {this.state.msgStatus} {this.state.strStatusText}</h4>
<h4> Output : {JSON.stringify(this.state.data)}</h4>
)
};
}
【问题讨论】:
-
它们被称为Function Components,并且由于引入了钩子,不是 functional
标签: javascript reactjs