【问题标题】:How React Redux component can subscribe on state changeReact Redux 组件如何订阅状态变化
【发布时间】:2017-08-03 23:18:37
【问题描述】:

我有一些“ChangeMainItem”操作(在我的情况下,它由外部系统或可能的组件之一调度)。这个动作(例如{type:Change_Main_Item, itemId:5})只更新reducer中的一个状态属性(例如mainItemId)。

我的组件 A 和 B 需要对这种状态变化做出反应:显示加载指示器、获取附加数据并显示结果。顺序操作可以通过一些异步操作库来完成 - 但是我应该将调度异步操作放在哪里?显然,我不能在组件 A 和 B 的 reducer 中调度异步操作,我也不想将原始操作更改为异步,以便它可以对我的组件发出任何必要的请求。

实现这一目标的正确方法是什么?

【问题讨论】:

    标签: javascript redux


    【解决方案1】:

    我建议使用 sagas 来监听您定义的操作并从那里管理您的异步调用/操作。 Redux-saga 很棒。

    import { put, takeEvery } from 'redux-saga/effects'
    import {Change_Main_Item, ANOTHER_ACTION, THIRD_ACTION} from '../actions'
    
    
    function* doSomething() {
          yield put({type: "ANOTHER_ACTION", payload: data});
    }
    
    function* doAnotherThing() {
          yield put({type: "THIRD_ACTION", payload: data});
    }
    
    function* mySaga() {
      yield takeEvery("Change_Main_Item", [doSomething, doAnotherThing]);
    }
    

    请看https://github.com/redux-saga/redux-saga

    【讨论】:

    • 那么使用 Redux-saga 我可以在 doSomething 中添加异步请求吗?像这样的东西? function* doSomething() {const data = yield call(Api.fetchData, action.payload.mainItemId); yield put({type: "DATA_FETCH_SUCCEEDED", data: data}); } 然后创建 sagaComponentA: yield takeEvery("Change_Main_Item", doSomethingA) (和组件 B 一样)
    • 是的.. Sagas 对于管理所有副作用(异步等)特别有用
    【解决方案2】:

    嗯,对于这样的问题,您有多种方法。

    您可以使用 redux-thunk,这样您就可以分派多个操作并让您的状态对所有此类分派做出反应。当您需要执行异步操作时,Thunk 中间件很有用。

    示例:

    function changeMainItem(id) {
      return (dispatch, getState) {
        dispatch(requestChangeMainItem); //This tells the state that it's loading some ajax; you presumably want to add some boolean, indicating a loading icon.
        return makeSomeRequest(id)
          .then(data => {
            dispatch(changeMainItem(data.id)) //presumably, this is where you update your item
            // perhaps dispatch another function to do more stuff.
          })
      }
    }
    

    然后,您需要确定哪些组件需要订阅/连接到您所在州的某些属性。

    了解async actionredux-thunksthis article on how to connect your components to your state

    【讨论】:

    • 我想过这个,但我不喜欢行动知道太多的想法。因此,如果我需要发出 10 个请求来显示 2-3 个组件,那么我需要创建这个非常大的 actionCreator(通过 redux-thunk 或其他)。我还是希望有办法订阅属性更新,让每个组件都知道要请求什么数据?
    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 2018-04-08
    • 2019-02-01
    • 2016-10-02
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多