代码之家  ›  专栏  ›  技术社区  ›  Rahul Singh

利用Redux-Saga实现组件与API的通信

  •  0
  • Rahul Singh  · 技术社区  · 6 年前

    使用某个服务层从组件调用。

    this 关于git的问题,如果这是可能的,有太多的排列和组合,我有点困惑。。

    this

    stackblitz .

    function* helloSaga() {
      return new Promise(function(resolve, reject) {
        resolve('start of new Promise');
      });
    }
    

    像这样访问它

    let response = dispatch(action('SHOW')).then(data => {
      console.log(data); // i cannot get this to work say if this were a api response .
    })
    

    什么也没发生。

    这个模式可以接受吗?如果是的话,我们怎么才能让它工作?我错过了什么

    getData() 应该足够了 componentDidMount() .

    0 回复  |  直到 6 年前
        1
  •  0
  •   Daniel    6 年前

    生成器函数并不像任何“常规”函数那样返回值(或者在您的情况下是promise)。它返回一个生成器对象,您可以暂停、继续、取消等。

    检查 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function

    在web应用程序中使用redux saga的方法是:

    1. action 喜欢 "SHOW" 在你的例子中
    2. 有一个 saga 行动起来 “显示”
    3. 这个 然后执行异步API请求
    4. 传奇 派遣另一个 (有点像 FETCH_SUCCEEDED
    5. 在reducer中处理操作并将响应存储在redux存储区中。

    一旦它存储在redux存储区中,您就可以从您想要的任何react组件中选择它(使用 connect

    下面是你的stackblitz和一个最小的例子:

    https://stackblitz.com/edit/react-redux-sagas-demo-app-4tpevb?file=index.js

    try{..}catch(){..} FETCH_FAILED 并在FE中显示错误消息(如果它影响到用户)。