我正在使用MERN堆栈编写计算器,但我的客户端和服务器是不同的项目。 React App在3030上运行,Node Backend在3000上运行。我能够从Node Backend检索正确的响应,但无法将其更新到商店,主要是因为问题的范围是' state&#39 ;或返回的数据。以下是我的代码段:
const calcReducer = (state = calcState, action) => {
switch(action.type){
case 'ADD_ELEM':
return {
...state,
value: state.value == 0 ? action.text : state.value + action.text
}
case 'CLEAR':
return{
...state,
value: 0
}
case 'EQUAL':
const url = 'http://localhost:3000/calculate';
superagent
.post(url)
.send({ exp : state.value })
.set('Accept', 'application/json')
.end((err,data) => {
if (err)
return state;
else {
console.log(state); //prints the old value of the state
//below prints the correct state value but returning the state from here doesn't work
console.log({
...state,
value : Number(JSON.parse(data.text).result)
})
}
})
return {
...state,
value : VALUE // how can the value be brought here from inside of else loop
}
default:
return state;
}
}
console.log语句里面' else'打印正确,但如果我从那里返回状态值没有效果。我目前正在返回的地方'州'对我来说没有用,并且返回的状态与控件进入案例之前的状态完全相同。有人可以解释我如何使用范围,因为我是ES6的新手吗?
EDIT1:
当我尝试采取' async-ness'退出减速机,并按以下方式进行更改:
const mapStateToProps = (state) => {
return{
value: state.value,
btns: state.btns
}
}
const mapDispatchToProps = (dispatch) => {
return{
addElem: (text) => {
dispatch({
type: 'ADD_ELEM',
text
})
},
clear: () => {
dispatch({
type: 'CLEAR'
})
},
equal: (value) => {
console.log(value)
superagent
.post('http://localhost:3000/calculate')
.send({ exp : value })
.set('Accept', 'application/json'))
.end((err,data) => {
dispatch({ type: 'EQUAL', JSON.parse(data.text).result })
})
}
}
}
在这种情况下,代码构建失败说: 模块构建失败:SyntaxError:意外的令牌(74:2)
72 |
73 | const mapStateToProps = (state) => {
> 74 | return{
| ^
75 | value: state.value,
76 | btns: state.btns
77 | }
答案 0 :(得分:1)
mapDispatchToProps
中存在语法错误,请尝试缩进代码,以便更容易识别它们。
const mapDispatchToProps = (dispatch) => {
return {
addElem: (text) => {
dispatch({
type: 'ADD_ELEM',
text
})
},
clear: () => {
dispatch({
type: 'CLEAR'
})
},
equal: (value) => {
console.log(value)
superagent
.post('http://localhost:3000/calculate')
.send({ exp : value })
.set('Accept', 'application/json')
.end((err,data) => {
dispatch({ type: EQUAL, result: JSON.parse(data.text).result })
})
}
};
};
答案 1 :(得分:-1)
return语句位于回调函数中。因此,您只能从回调函数返回。您可能应该将它包装在Promise中,如下所示。
return new Promise((resolve, reject) => {
superagent(...)
...
.end((err, data) => {
if (err)
reject(state);
else {
resolve({
...state,
value : Number(JSON.parse(data.text).result)
});
}
});
});