【发布时间】:2016-02-24 12:17:23
【问题描述】:
在以下示例中,如何在地理定位请求期间禁用该按钮?在初始化时未设置 this.props.inProgress ,我想在请求 getCurrentPosition 时禁用按钮并在 RECEIVE_LOCATION 解决时启用。什么是正确的做法?我是否要使用状态并将道具复制到 GeoButton?
export function getGeolocation() {
return dispatch => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
dispatch({
type: 'RECEIVE_LOCATION',
coords: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
inProgress: false,
},
});
});
}
}
}
export function geolocation(state={}, action) {
switch (action.type) {
case 'RECEIVE_LOCATION':
var newState = action.coords;
return newState;
default:
return state;
}
}
class GeoButton extends React.Component {
constructor(props) {
super(props);
}
findLocation(e) {
e.preventDefault();
this.props.dispatch(getGeolocation());
}
render() {
console.log(this.props); // on init geolocation object is empty
var self = this;
return (
<div>
<button type="button" onClick={this.findLocation} disabled={self.props.geolocation.inProgress}>Get location</button>
</div>
)
}
}
export default connect(state => ({
geolocation: state.geolocation
}))(GeoButton); // just gives it dispatch()
【问题讨论】:
-
你不能使用 inProgress 标志吗?像 disabled="inProgress"
-
在构造函数中设置与预期数据相对应的状态对象并在解决时用该数据替换该状态不是更好吗?我不确定在这种情况下哪种方法是正确的,当前的解决方案不起作用。
标签: javascript reactjs redux redux-thunk