Edw*_*ith 12 javascript reactjs
所以我有一大堆数据,我正在从API中检索.我相信问题是我的组件在从promise接收数据之前调用renderMarkers函数.
所以我想知道如何在调用renderMarkers函数之前等待完全解析数据的承诺?
class Map extends Component {
componentDidMount() {
console.log(this.props)
new google.maps.Map(this.refs.map, {
zoom: 12,
center: {
lat: this.props.route.lat,
lng: this.props.route.lng
}
})
}
componentWillMount() {
this.props.fetchWells()
}
renderMarkers() {
return this.props.wells.map((wells) => {
console.log(wells)
})
}
render() {
return (
<div id="map" ref="map">
{this.renderMarkers()}
</div>
)
}
}
function mapStateToProps(state) {
return { wells: state.wells.all };
}
export default connect(mapStateToProps, { fetchWells })(Map);
Run Code Online (Sandbox Code Playgroud)
Bil*_*mad 27
对于带钩子的功能组件:
function App() {
const [nodes, setNodes] = useState({});
const [isLoading, setLoading] = useState(true);
useEffect(() => {
getAllNodes();
}, []);
const getAllNodes = () => {
axios.get("http://localhost:5001/").then((response) => {
setNodes(response.data);
setLoading(false);
});
};
if (isLoading) {
return <div className="App">Loading...</div>;
}
return (
<>
<Container allNodes={nodes} />
</>
);
}
Run Code Online (Sandbox Code Playgroud)
Lio*_*l T 21
您可以执行以下操作来显示Loader,直到获取所有信息:
class Map extends Component {
constructor () {
super()
this.state = { wells: [] }
}
componentDidMount() {
this.props.fetchWells()
.then(res => this.setState({ wells: res.wells }) )
}
render () {
const { wells } = this.state
return wells.length ? this.renderWells() : (
<span>Loading wells...</span>
)
}
}
Run Code Online (Sandbox Code Playgroud)
在 API 调用完成之前调用渲染函数是可以的。这wells是一个空数组(初始状态),您只需渲染任何内容。并且在从 API 接收到数据后,你的组件会因为 props(redux store)的更新而自动重新渲染。所以我没有看到问题。
如果你真的想在接收 API 数据之前阻止它渲染,只需在你的渲染函数中检查,例如:
if (this.props.wells.length === 0) {
return null
}
return (
<div id="map" ref="map">
{this.renderMarkers()}
</div>
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32573 次 |
| 最近记录: |