我正在使用fetch进行异步调用,然后尝试通过根据返回的json数据的结果调度操作来设置状态。
我正在使用QR码阅读器来读取传递给我的didScan方法的代码。
didScan(code) {
if (this.state.showCamera){
this.props.pushNewRoute('finder');
getAppointment(code)
.then((appointment)=>{
if (appointment.valid){
this.props.appointmentDetails(appointment);
this.props.resetRoute('summary');
}else{
this.props.resetRoute('error');
}
})
.catch((error) => {
this.props.resetRoute('error');
});
this.setState({showCamera: false});
}
}
我正在使用react-redux将我的行动绑定到我的调度员:
function bindActions(dispatch){
return {
resetRoute:(route)=>dispatch(resetRoute(route)),
pushNewRoute:(route)=>dispatch(pushNewRoute(route)),
appointmentDetails:(details)=>dispatch(appointmentDetails(details))
}
}
export default connect(null, bindActions)(Scanner);
但是当我的getAppointment服务返回promise时,它在尝试进行路由时失败。
this.props.resetRoute('summary');
错误是
可能未处理的承诺拒绝{id:0} 减速器可能不会发送动作
当我把它从Promise .then()块中删除时,我的reducers都没有调度任何动作,代码工作正常。
以下是完整性的简单getAppointment提取服务:
export function getAppointment(id:string) {
return fetch('http://myurl/' + id + '/')
.then((response) => response.json())
.catch((error) => {
console.error(error);
return error;
});
}
非常感谢任何帮助。
答案 0 :(得分:0)
我不确定你的语法绑定动作是什么,以前没见过。这是我为项目做的代码示例,我在其中执行get请求,然后将响应设置为状态:
SearchBar.jsx (这会向Solr发出一个http请求并获取一个JSON对象,然后将该对象设置为状态)
import React, {Component} from 'react';
import httpClient from 'axios';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {setResponse} from '../actions/index'
class SearchBar extends Component {
constructor(props) {
super(props);
this.search = this.search.bind(this);
}
search() {
let q = document.getElementById('searchbar').value;
httpClient(`/search?q=${q}`, { baseURL: window.location.href })
.then( resp => {
console.log(resp);
this.props.setResponse(resp);
});
}
render() {
return (
<div>
<input type='text' id='searchbar'/>
<button onClick={this.search}>Search</button>
</div>
);
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({setResponse: setResponse}, dispatch);
}
export default connect(null, mapDispatchToProps)(SearchBar);
这是行动:
export const setResponse = (res) => {
return {
type: 'RESPONSE_RECEIVED',
payload: res
}
};
这是减速器:
export default function (state = null, action) {
switch (action.type) {
case 'RESPONSE_RECEIVED':
return action.payload;
break;
}
return state;
}
导出到组合函数(虽然只有一个reducer atm):
import {combineReducers} from 'redux';
import ResponseReducer from './reducer-response';
const allReducers = combineReducers({
response: ResponseReducer
});
export default allReducers;