【问题标题】:what's the difference between these two callback in react-redux?react-redux 中这两个回调有什么区别?
【发布时间】:2017-05-04 07:36:57
【问题描述】:

我正在通过 Udemy 课程学习 react-redux。满足此代码,

 export function createPost(value, callback){
       const request = axios.post(url, value).then(() => callback());
    }

为什么不把回调这样放

const request = axios.post(url, value).then(callback);

编辑

在视频中他们这样称呼这个函数

this.props.createPost(value, () => this.props.history.push('/'));

2.

因为他们打电话给this.props.createPost(value, () => this.props.history.push('/'));

我以为回调已经是一个函数了 () => this.props.history.push('/') ;

那么为什么他们在createPost by Promise.then(() => callback()) 的定义中再次包装了回调

在我看来,只需像Promise.then(callback) 这样的回调就可以了。

我错了吗?

【问题讨论】:

  • 这也可以:axios.post(url, value).then(callback); 但在这种情况下,您不能将某些值传递给该函数,但在第一种情况下,您可以:const request = axios.post(url, value).then(() => callback('success'));

标签: reactjs promise redux react-redux


【解决方案1】:

如果您仔细观察,您的函数调用需要一个参数,这意味着如果您在末尾附加括号,它将立即被调用:

this.props.history.push('/')

如果你尝试这样做:

this.props.createPost(value, this.props.history.push('/')); // without the () =>

函数history.push 将被立即调用,你正在做的是上下文绑定,通过创建一个 lambda 函数你正在延迟执行并添加一个常量参数'/'。

实现此目的的另一种方法:

this.props.createPost(value, this.props.history.push.bind(null, '/')

阅读Bind

如果你的函数没有带任何参数,那么你可以做任何你想做的事(没有括号 ofc)

this.props.createPost(value, this.props.anotherFunction) // anotherFunction does not take any params, and does can be passed as is

【讨论】:

  • 但在 EDIT 中,据我了解,他们已经使用组合函数 this.props.createPost(value, () => this.props.history.push('/')) 调用函数 createPost ,为什么又在函数定义Promise.then(() => callback()) 中调用函数?
  • 对我的 cmets 有任何想法吗?我
  • 正如我所说:如果您不将回调函数包装在 lambda 函数中,它将立即执行,您想要的是在承诺返回后延迟执行并将参数“/”绑定到函数调用
  • 但我认为回调已经被() => this.props.history.push('/') 包裹起来了,是否有必要再次被() => callback() 包裹起来?
  • 如果您将回调创建为:const callback = () => this.props.history.push('/'),然后执行this.props.createPost(value, callback);,您所做的是完全相同的事情,您只是将定义移到外部函数的声明之外。
猜你喜欢
  • 2018-01-13
  • 2016-11-19
  • 2016-08-05
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 2018-07-16
  • 2012-06-12
  • 2016-10-06
相关资源
最近更新 更多