我有2个状态完整的组件App.js和LoadBoard.jsx。我想在LoadBoard中获取数据并在App.js中显示它。问题在于LoadBoard.jsx在获取数据之前正在显示数据。在此应用程序中,我将获取大约6次数据,因此我希望可以在不同的组件中代替App.js
我的想法
很明显,在App.js中,我可以将if语句放入render中,以仅在获取后才渲染值。问题是我无权访问App.js中的positionToId。我应该将positionToId存储在App.js中而不是LoadBoard.jsx中吗?
if(this.state.positionToID.length > 0){
<LoadBoard
apiBase = {this.state.apiBase}/>
}
APP.JS
render(){
}
return(
<div className="col-xs-10">
<div id="game_board" className="row">
<LoadBoard
apiBase = {this.state.apiBase}
/>
)
LoadBoard.jsx
class LoadBoard extends Component {
constructor(props){
super(props)
this.state = {
positionToId: [],
}
}
componentDidMount(){
this.setState({loading: true});
Axios.get(this.props.apiBase + 'configuration')
.then(response => {
let idArray = [];
for (let index = 0; index < response.data.slots; index++) {
idArray.push(response.data.positionToId[index]);
this.setState({loading: false});
}
this.setState({positionToId: idArray})
console.log(this.state.positionToId);
})
.catch(error => {
console.log(error);
})
}
render() {
let LoadBoard = <h1>This is displayed</h1>;
if(this.state.positionToId.length> 0){
return <h1>This is not displayed</h1>
}
return (
<div>
{LoadBoard}
</div>
)
}
}