我正在使用 google 的自动完成 API 来改进表单中的地址输入。
我正在使用 GoogleMapsLoader 加载器,它在加载后调度动作:
GoogleMapsLoader.onLoad(function() {
store.dispatch(GoogleActions.loaded());
});
在 React 组件中,我有以下输入:
if (google.status === 'LOADED') {
inputGoogle = <div>
<label htmlFor={`${group}.google`}>Auto Complete:</label>
<input ref={(el) => this.loadAutocomplete(el)} type="text" />
</div>;
} else {
inputGoogle = '';
}
loadAutocomplete 方法(不确定这是否是最好的方法):
loadAutocomplete(ref) {
if (!this.autocomplete) {
this.search = ref;
this.autocomplete = new google.maps.places.Autocomplete(ref);
this.autocomplete.addListener('place_changed', this.onSelected);
}
},
更新:
使用下面的答案我做了以下事情:
const GoogleReducer = (state = initialState, action) => {
switch (action.type) {
case 'GOOGLE_LOADED':
return Object.assign({}, state, {
status: 'LOADED',
connection: 'ONLINE'
});
case 'GOOGLE_OFFLINE':
return Object.assign({}, state, {
connection: 'OFFLINE'
});
case 'GOOGLE_ONLINE':
return Object.assign({}, state, {
connection: 'ONLINE'
});
default:
return state;
}
};
const GoogleActions = {
loaded: () => {
return (dispatch) => {
dispatch({
type: 'GOOGLE_LOADED',
});
};
},
onOnline: () => {
return (dispatch) => {
window.addEventListener('online', function() {
dispatch({
type: 'GOOGLE_ONLINE'
});
});
};
},
onOffline: () => {
return (dispatch) => {
window.addEventListener('offline', function() {
dispatch({
type: 'GOOGLE_OFFLINE'
});
});
};
}
};
React 组件内部:
if (google.status === 'LOADED' && google.connection === 'ONLINE') {
inputGoogle = <div>
<label htmlFor={`${group}.google`}>Auto Complete:</label>
<input ref={(el) => this.loadAutocomplete(el)} name={`${group}.google`} id={`${group}.google`} type="text" onFocus={this.clearSearch}/>
</div>;
} else {
inputGoogle = <p>Auto Complete not available</p>;
}
到目前为止有效。