Javascript 基于道具发出条件Api请求

Javascript 基于道具发出条件Api请求,javascript,reactjs,fetch,Javascript,Reactjs,Fetch,我有一个极简登陆页面,有两个文本和一个div,包含两个按钮。单击其中一个按钮后,我希望使用作为道具传递的位置或硬编码到App组件中的默认位置渲染App组件 我已经使用地理定位API和窗口导航器获取了位置,并将其传递到App组件中,如果单击第一个按钮,如下所示: if (this.state.shouldShowMain){ return ( <App/> ) // no props } else if (this.state.shouldShowMainWit

我有一个极简登陆页面,有两个文本和一个div,包含两个按钮。单击其中一个按钮后,我希望使用作为道具传递的位置或硬编码到
App
组件中的默认位置渲染
App
组件

我已经使用地理定位API和窗口导航器获取了位置
,并将其传递到
App
组件中,如果单击第一个按钮,如下所示:

if (this.state.shouldShowMain){
        return ( <App/> ) // no props
    } else if (this.state.shouldShowMainWithProps){
        const { lat, lng } = this.state.mLocation;
        return ( <App
            latitude={lat}
            longitude={lng} // props to App component
        />)
    }
在应用程序组件中,我试图在进行api调用获取标记之前区分这两种状态,如下所示:

 componentDidMount() {

    if (this.props){
        const { latitude, longitude } = this.props;
        // console.log(this.props);

        fetch(
            // 'https://api.foursquare.com/v2/venues/search?ll= 12.917137,77.622791' +
            'https://api.foursquare.com/v2/venues/search?ll=' + latitude + ',' + longitude +
            '&query=atm&client_id=LVN4FEBT5Q0DBIQ2JOP4KYZ1LOEXREFRLOXV5UXAQWHUF14V' +
            '&client_secret=HZRYTMFJRS4N0R50IEZR04JXSO1KWVJWC015VTYLCCCG3C0U&v=20181101')
            .then(response => response.json())
            .then(data => {

                const atms = data.response.venues;
                const markers = atms.map( (item) => {
                    return {
                        lat: item.location.lat,
                        lng: item.location.lng
                    }
                });

                this.setState({
                    atms,
                    markers
                })
            })
            .catch(err => {
                this.setState({apiError: true});
                throw err;
            });
    } else {
        // no probs, fetching from silk board

        fetch(
            // 'https://api.foursquare.com/v2/venues/search?ll=' + latitude + ',' + longitude +
            'https://api.foursquare.com/v2/venues/search?ll= 12.917137,77.622791' +
            '&query=atm&client_id=LVN4FEBT5Q0DBIQ2JOP4KYZ1LOEXREFRLOXV5UXAQWHUF14V' +
            '&client_secret=HZRYTMFJRS4N0R50IEZR04JXSO1KWVJWC015VTYLCCCG3C0U&v=20181101')
            .then(response => response.json())
            .then(data => {

                const atms = data.response.venues;
                const markers = atms.map( (item) => {
                    return {
                        lat: item.location.lat,
                        lng: item.location.lng
                    }
                });

                this.setState({
                    atms,
                    markers
                })
            })
            .catch(err => {
                this.setState({apiError: true});
                throw err;
            });
    }

}
const { lat, lng } = this.state.mLocation;
return (
    <App latitude={lat} longitude={lng}/>
);
我测试它时的情况是,当我选择“获取我的位置”按钮时,它获取应用程序组件中硬编码的位置,即else部分,当我在没有道具的情况下单击按钮时,应用程序崩溃,因为它期望某个值,而实际上不应该有

它在相反的情况下工作,因此api调用失败。我该如何解决这个问题?我愿意对问题进行编辑,以适应所要求的任何细节。谢谢

根据这些好的建议,我得到的答复是问题已经解决了一半。现在的问题是从coords渲染正确的贴图。这是我的实现:

<div className="mapContainer">

                    <MapView
                        atms={this.state.atms},
                        markers={this.state.markers}
                        apiError={this.state.apiError}
                        filteredAtms={filteredAtms}/>
                </div>
我如何适应这个?我是否使用相同的方法在该组件上设置默认道具,或者使用其他方法。谢谢。

您可以为应用程序组件定义,如果您不将纬度和经度传递给组件,它将使用默认值

class App extends React.Component {
  render() {
    return (
      ...
    );
  }
}

App.defaultProps = {
    latitude: 12.917137,
    longitude: 77.622791,
}
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            latitude: this.props.latitude || 123.45 // default value
            longitude: this.props.longitude || 456.78 // default value
        };
    }
    componentDidMount() {
        const { latitude, longitude } = this.state;
        fetch('https://api.foursquare.com/v2/venues/search?ll=' + latitude + ',' + longitude +
            // other code...
    }
}

您可以传递@oliver.voron提到的默认道具,或者执行以下简单操作:

const latitude = this.props.latitude || 'defaultLatitude';
const longitude = this.props.longitude || 'defaultLongitude';

您可以按如下方式呈现
应用程序
组件:

 componentDidMount() {

    if (this.props){
        const { latitude, longitude } = this.props;
        // console.log(this.props);

        fetch(
            // 'https://api.foursquare.com/v2/venues/search?ll= 12.917137,77.622791' +
            'https://api.foursquare.com/v2/venues/search?ll=' + latitude + ',' + longitude +
            '&query=atm&client_id=LVN4FEBT5Q0DBIQ2JOP4KYZ1LOEXREFRLOXV5UXAQWHUF14V' +
            '&client_secret=HZRYTMFJRS4N0R50IEZR04JXSO1KWVJWC015VTYLCCCG3C0U&v=20181101')
            .then(response => response.json())
            .then(data => {

                const atms = data.response.venues;
                const markers = atms.map( (item) => {
                    return {
                        lat: item.location.lat,
                        lng: item.location.lng
                    }
                });

                this.setState({
                    atms,
                    markers
                })
            })
            .catch(err => {
                this.setState({apiError: true});
                throw err;
            });
    } else {
        // no probs, fetching from silk board

        fetch(
            // 'https://api.foursquare.com/v2/venues/search?ll=' + latitude + ',' + longitude +
            'https://api.foursquare.com/v2/venues/search?ll= 12.917137,77.622791' +
            '&query=atm&client_id=LVN4FEBT5Q0DBIQ2JOP4KYZ1LOEXREFRLOXV5UXAQWHUF14V' +
            '&client_secret=HZRYTMFJRS4N0R50IEZR04JXSO1KWVJWC015VTYLCCCG3C0U&v=20181101')
            .then(response => response.json())
            .then(data => {

                const atms = data.response.venues;
                const markers = atms.map( (item) => {
                    return {
                        lat: item.location.lat,
                        lng: item.location.lng
                    }
                });

                this.setState({
                    atms,
                    markers
                })
            })
            .catch(err => {
                this.setState({apiError: true});
                throw err;
            });
    }

}
const { lat, lng } = this.state.mLocation;
return (
    <App latitude={lat} longitude={lng}/>
);

好的,我已经解决了从哪个端点获取数据的问题,方法是在应用程序组件中添加一个属性(fromLocation)from state,但地图只呈现硬编码值的属性。我解决了这个问题吗?我也解决了这个地图呈现问题,但我会根据所有这些建议修改代码,使事情更清晰一些。谢谢大家。谢谢@oliver.voron。我已经解决了这个问题,但你的方法更优雅。现在最紧迫的问题是如何根据坐标正确地渲染地图,到目前为止,它仍在使用前一个坐标。