Redux Actions 必须是普通对象。使用自定义中间件进行异步操作
Redux Actions must be plain objects. Use custom middleware for async actions
密码是:
测试组件:
import {add} from './../actions/';
class Test extends Component{
_add = (){
this.props.add(1);
}
render(){
<button onClick={this._add}>add</button>
}
}
const mapStateToProps = ()=>({
haha:'haha'
});
export default connect(
mapStateToProps,
{add}
)(Test)
操作数:
export const add = value => (dispatch) =>{
dispatch({
type:'ADD',
value:value
})
}
我点击添加按钮出现这个错误!
有什么问题?
我看了 createStore.js 和 console.log(action)
。它显示了一个功能。
但是Redux的例子不是一个函数。我的代码几乎一样。
您只是缺少箭头函数中的箭头 =>
:
export const add = value => (dispatch) => {
dispatch({
type:'ADD',
value:value
})
}
你应该这样写你的 action creator:
export const add = value =>
({
type: 'ADD',
value: value
});
将动作创建器连接到组件的方式(使用快捷符号 { add }
作为第二个参数传递给 connect
)允许您省略 dispatch
,因为 connect
以这种方式调用时会自动将您的动作创建器包装到 dispatch
调用中。
如果您使用 redux-thunk 作为中间件,它将处理调度的函数操作....
另一个是 redux-promise,它会做一些类似 thunk 的事情......但有承诺
更新:
这是处理异步的模型
export const add = value => (dispatch) => {
... do something async
}
点赞:
export const add = value => (dispatch) => {
http.get('/path')
.then(json =>
dispatch({type: 'RESULT', payload: json}));
}
您的操作没有异步调用,因此可以这样写:
export const add = value => ({
type:'ADD',
value:value
})
密码是:
测试组件:
import {add} from './../actions/';
class Test extends Component{
_add = (){
this.props.add(1);
}
render(){
<button onClick={this._add}>add</button>
}
}
const mapStateToProps = ()=>({
haha:'haha'
});
export default connect(
mapStateToProps,
{add}
)(Test)
操作数:
export const add = value => (dispatch) =>{
dispatch({
type:'ADD',
value:value
})
}
我点击添加按钮出现这个错误!
有什么问题?
我看了 createStore.js 和 console.log(action)
。它显示了一个功能。
但是Redux的例子不是一个函数。我的代码几乎一样。
您只是缺少箭头函数中的箭头 =>
:
export const add = value => (dispatch) => {
dispatch({
type:'ADD',
value:value
})
}
你应该这样写你的 action creator:
export const add = value =>
({
type: 'ADD',
value: value
});
将动作创建器连接到组件的方式(使用快捷符号 { add }
作为第二个参数传递给 connect
)允许您省略 dispatch
,因为 connect
以这种方式调用时会自动将您的动作创建器包装到 dispatch
调用中。
如果您使用 redux-thunk 作为中间件,它将处理调度的函数操作....
另一个是 redux-promise,它会做一些类似 thunk 的事情......但有承诺
更新:
这是处理异步的模型
export const add = value => (dispatch) => {
... do something async
}
点赞:
export const add = value => (dispatch) => {
http.get('/path')
.then(json =>
dispatch({type: 'RESULT', payload: json}));
}
您的操作没有异步调用,因此可以这样写:
export const add = value => ({
type:'ADD',
value:value
})