【发布时间】:2017-10-07 08:26:48
【问题描述】:
我正在使用 MERN 堆栈开发计算器,但我的客户端和服务器是不同的项目。 React App 在 3030 上运行,Node Backend 在 3000 上运行。我能够从 Node Backend 检索正确的响应,但无法将其更新到商店,主要是由于“状态”范围或返回数据的问题。下面是我的代码 sn-p :
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;
}
}
'else' 中的
console.log 语句可以正确打印,但如果我从那里返回状态值则无效。我目前返回“状态”的地方对我来说不起作用,返回的状态与控件进入机箱之前的状态完全相同。有人可以解释一下我是 ES6 新手如何使用范围吗?
编辑1:
当我尝试从减速器中取出“异步”并进行如下更改时:
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: Unexpected token (74:2)
72 |
73 | const mapStateToProps = (state) => {
> 74 | return{
| ^
75 | value: state.value,
76 | btns: state.btns
77 | }
【问题讨论】:
-
你正试图在你的 reducer 中做一些带有副作用的异步操作。这与需要做的事情完全相反。我建议你在使用它之前阅读文档redux.js.org
-
我可以理解,这可能不是最好的方法,我现在正在阅读 redux 教程和文档,但我想知道这是否真的是范围问题,可以吗?在这种情况下使用跨越“case statement”范围的变量可以轻松解决?
-
没问题,问题是:你的reducer是同步的,它需要一个状态,一个动作,并且必须立即返回新的状态。这不仅仅是作用域的问题,而是时间的问题,你的回调
.end((err,data) =>会在你的reducer 的return之后执行很长时间。尝试在 reducer 之外调度同步操作。superAgent.post().end(value => store.dispatch({ type: EQUAL, value }),看看redux.js.org/docs/advanced/AsyncFlow.html -
这是一个不错的技巧,但我再次面临同样的问题,当我从回调内部执行“调度”时,它并没有真正发生并且代码构建失败,我将更新上面的代码。
-
这是一个语法错误,请再次检查您的代码
标签: ecmascript-6 redux react-redux