简体   繁体   English

React Redux组件如何订阅状态更改

[英]How React Redux component can subscribe on state change

I have some "ChangeMainItem" Action (in my case it is dispatched by external system or possibly one of components). 我有一些“ ChangeMainItem”操作(在我的情况下,它是由外部系统或可能的组件之一调度的)。 This action (eg {type:Change_Main_Item, itemId:5} ) updates only one property of state in reducer (eg mainItemId ). 此操作(例如{type:Change_Main_Item, itemId:5} )仅更新化mainItemId器中的状态的一个属性(例如mainItemId )。

My Component A and B needs to react on this state change: show loading indicator, fetch additional data and show results. 我的组件A和B需要对此状态做出反应:显示加载指示器,获取其他数据并显示结果。 Sequential actions can be done via some async action library - but where should I place dispatching async action? 可以通过一些异步操作库来执行顺序操作-但是我应该将调度异步操作放在哪里? Obviously, i can't dispatch async action in reducer of Component A and B, neither i want to change original Action to async so it can make any necessary requests for my components. 显然,我无法在组件A和B的化简器中调度异步操作,也不想将原始Action更改为异步,以便它可以对我的组件提出任何必要的请求。

What is the right way to achieve this? 什么是实现此目标的正确方法?

I suggest using sagas to listen to your defined actions and manage your async calls/actions from there. 我建议使用sagas来侦听您定义的操作并从那里管理异步调用/操作。 Redux-saga is awesome. 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]);
}

Please see https://github.com/redux-saga/redux-saga 请参阅https://github.com/redux-saga/redux-saga

Well, you have multiple approaches to such a question. 好吧,您可以通过多种方法来解决这个问题。

You can use a redux-thunk so you can dispatch multiple actions and have your state react to all such dispatches. 您可以使用redux-thunk,这样您可以调度多个操作,并使您的状态对所有此类调度作出反应。 Thunk middleware is useful when you need to perform async actions. 当您需要执行异步操作时,Thunk中间件非常有用。

example: 例:

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.
      })
  }
}

You then will need to figure out which components need to be subscribed/connected to certain properties in your state. 然后,您将需要确定哪些组件需要订阅/连接到状态中的某些属性。

Read about async action , redux-thunks , and this article on how to connect your components to your state 阅读有关异步操作redux-thunks的信息 ,以及有关如何将组件连接到状态的本文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM