【问题标题】:Redux Saga- return the result to callee function instead of dispatching new actionRedux Saga - 将结果返回给被调用函数而不是调度新动作
【发布时间】:2018-07-13 09:59:13
【问题描述】:

我正在将我的 react 项目转移到 redux 和 redux-saga。最初,我调用异步方法来获取大型数据集,然后将其设置为本地状态,如下所示:

// Component.jsx
componentDidMount() {
   const dataPromise = this.getTableData()
   const data = await dataPromise
   this.setState({ data })
}

getTableData = async() => {
   const response = await APIUtils.getTableData()
   let data = null
   if (response && response.code === "200") {
      data = response.data
   }
   return data
}

现在使用 redux,我正在这样更改它

// Component.jsx
componentDidMount() {
  const data = this.props.getTableData() // how to get data here?
  this.setState({ data })
}

// ActionCreator.js
function getTableData() {
   return {
     type: "GET_TABLE_DATA"
   }
}

// saga.js
function *getTableData() {
   try {
        const response = yield call(APIUtils.getTableData)
        ...
        // here I want to send this response.data to my comp without calling store action as the dataset is large and it is read-only.

    } catch (err) {
        yield put(showError(false))
    }
}

export default function* root() {
  yield all([
    takeLatest("GET_TABLE_DATA", getTableData)
  ])
}

我是 redux-saga 的新手,谁能告诉我最好的方法是什么。

【问题讨论】:

    标签: reactjs redux yield redux-saga


    【解决方案1】:

    您需要发送一个操作来更新您的商店。然后将组件连接到 store 并从 store 中获取数据。

    【讨论】:

    • 整个想法是我不想将这些数据保存在存储中,因为数据集很大,并且不会更改或在其他任何地方使用。
    • 但是如果不使用存储,数据无论如何都会存储在您的组件中。如果你不想一直把它放在 store 里,你可以在你的组件被卸载时调度一个 action 把它从 store 中删除。
    • 是的,基本上我只想将数据保持在组件状态。我可以通过将响应数据直接传递给调用它的实例来避免将数据存储在存储中并在组件卸载时删除吗?我应该在调度的动作中使用回调方法吗?
    • 如果你不想使用 store 那么你不需要 sagas 和 action 只需使用你以前的方法并直接从你的组件调用 api。
    • 说得好,如果你想在 store 中保存数据,使用 saga 来更新 store.... .
    猜你喜欢
    • 2021-12-28
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    相关资源
    最近更新 更多