我有以下代码:
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import axios from "axios";
var config = {
headers: {
Accept: "application/json; odata=verbose",
Authorization: "Bearer " + access_token,
},
};
class Searchbar extends React.Component {
async componentWillMount() {
await axios.get(contracts, config).then((res) => {
this.setState({ allContracts: res.data });
});
}
render() {
return (
<div className="searchbar_wrapper">
<Autocomplete
freeSolo
id="contract-search-bar"
disableClearable
options={contracts.map((option) => option.name)}
onChange={(event, value) => {
let selectedContractID =(value)
}}
renderInput={(params) => (
<TextField
{...params}
label="Search"
margin="normal"
variant="outlined"
InputProps={{ ...params.InputProps, type: "search" }}
/>
)}
/>
</div>
);
}
}
export default Searchbar;
我正在使用组件安装,因为我希望此函数在渲染组件之前先进行调用... axios调用将得到如下结果:
results = [
{ name: "aaa" },
{ name: "bb" },
{ name: "cccc" },
];
结果将超过500个条目。
我遇到的问题是,当组件渲染时,它一直在说:
Cannot read property 'allContracts' of null
这样做的原因是因为axios函数尚未完成获取结果的过程...
请让我知道如何延迟渲染并等待axios首先获得结果然后继续
这会有所帮助。无需ComponentWillMount。还需要进行错误处理。
state = {
allContracts: null,
error: false
}
componentDidMount(){
axios.get(contracts, config)
.then((res) => {
this.setState({ allContracts: res.data });
})
.catch((err) => this.setState({error: true}))
}
render() {
if(!state.allContracts && !this.state.error){
return null; // add a spinner or something until the posts are loaded
}
if(this.state.error){
return 'Something wrong happened...' // just an example of error
}
return // this will run after the posts are loaded
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句