我正在构建一个天气应用程序,我正在寻找一些最佳实践建议,这些建议是在父组件进行异步调用之后,根据从父组件发送的道具来更新子组件中的状态。
我有一个父组件,该父组件在componentDidMount()方法中对进行异步/等待调用,navigator.geolocation并返回纬度和经度,这些纬度和经度要作为道具发送给子组件。然后,在子组件中,我需要使用道具的经纬度和经度对OpenWeatherMap API进行异步/等待调用。然后,我需要setState()使用response。我不能componentDidMount()在子级中使用它,因为它会在父级异步/等待调用返回之前挂载。
问题是应用程序流程:父组件安装和渲染,并以形式将道具发送给子组件null。子组件将通过nullprops进行安装和渲染。然后,异步/ AWAIT返回在父集的响应lat,并long从响应于状态下componentDidMount(),父母重新呈现,并用正确的值作为发送道具子lat和long。子组件会更新道具中的正确值。现在,在这一点上我需要setState()使用这些道具,但是如果componentDidUpdate()不重新渲染为无限循环,我显然无法做到。
那么,什么是完成此任务的好方法?
父组件:
class Container extends React.Component {
state = {
cityState: {
city: "",
state: ""
},
latLong: {
lat: null,
long: null
}
};
componentDidMount() {
this.getCityAndState();
}
getCityAndState() {
let latlng = "";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(async position => {
latlng = `${position.coords.latitude},${position.coords.longitude}`;
const response …Run Code Online (Sandbox Code Playgroud)