【发布时间】:2017-01-12 19:03:46
【问题描述】:
我是 React Native 的新手,我不知道我在哪里犯了错误。 即在我的 React Native 应用程序中,当我进行异步函数调用时,我得到了
Reducer 不能调度操作
错误。
这是我正在调用的组件
componentDidMount(){
this.initializeOverview().done();
}
async initializeOverview() {
await this.props.getExpensesSum();
}
但是,如果我在 getExpensesSum() 中调用没有 dispatch(getExpensesSumRequest()) 的相同函数,则一切正常。我之所以调用 getExpensesSumRequest() 是因为我想在等待数据时显示加载指示器。
更让我困惑的是**当我通过单击按钮调用 getExpensesSum() 时它正在工作**
这是我调用 REST API 的操作函数,内部是有问题的 getExpensesSumRequest() 函数。
export function getExpensesSum() {
return (dispatch) => {
**dispatch(getExpensesSumRequest())**
return fetch(URL + "/api/expenses/sum/", {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => response.json().then(json => ({
json,
response
})))
.then(({
json,
response
}) => {
if (response.ok === false) {
return Promise.reject(response, json)
}
return json
})
.then(
// success
data => {
dispatch(getExpensesSumSuccess(data));
},
// failure
(data) => dispatch(getExpensesSumFailure(data.status || 'Something failed'))
).catch((error) => console.warn("fetch error:", error))
}
}
分派的方法
export function getExpensesSumSuccess(expSum) {
return {
type: GET_EXPENSESSUM_SUCCESS,
expSum
}
}
export function getExpensesSumRequest() {
return {
type: GET_EXPENSESSUM_REQUEST,
}
}
export function getExpensesSumFailure(error) {
return {
type: GET_EXPENSESSUM_FAILURE,
error
}
}
这是我的减速器
import {
GET_EXPENSESSUM_REQUEST,
GET_EXPENSESSUM_SUCCESS,
GET_EXPENSESSUM_FAILURE
} from '../actions/overview'
function expensesSum(state = {
loadingExpensesSum: false,
expensesSum: {'Sum':0}
}, action) {
switch(action.type) {
case GET_EXPENSESSUM_REQUEST:
return {
loadingExpensesSum: true, // Show a loading indicator.
expensesSum:{'Sum':0}
}
case GET_EXPENSESSUM_FAILURE:
return {
loadingExpensesSum: false,
error: action.error
}
case GET_EXPENSESSUM_SUCCESS:
return {
loadingExpensesSum: false,
expensesSum: action.expSum,
}
default:
return state
}
}
export default expensesSum
我正在使用 react-redux 将我的操作绑定到我的调度程序,如下所示:
function mapDispatchToProps(dispatch) {
return {
getExpensesSum: () => dispatch(getExpensesSum()),
};
}
function mapStateToProps(state) {
return {
name: state.user.name,
expensesSum:state.expensesSum.Sum,
};
}
非常感谢任何帮助。
附:这是堆栈跟踪
【问题讨论】:
-
发生该错误时堆栈跟踪是什么样的?
-
我添加了两张带有堆栈跟踪的图片i.stack.imgur.com/HLjZJ.pngi.stack.imgur.com/QDEBA.png
标签: javascript reactjs react-native redux react-redux