Subscribe to single property change in store in Redux

前端 未结 4 1809
情歌与酒
情歌与酒 2020-12-02 07:04

In Redux I can easily subscribe to store changes with

store.subscribe(() => my handler goes here)

But what if my store is full of differ

4条回答
  •  春和景丽
    2020-12-02 07:32

    Redux only offers a single generic way to know when the store has updated: the subscribe method. Callbacks to subscribe do not get any info on what might have changed, as the subscribe API is deliberately low-level, and simply runs each callback with no arguments. All you know is that the store has updated in some way.

    Because of that, someone has to write specific logic to compare old state vs new state, and see if anything has changed. You could handle this by using React-Redux, specifying a mapStateToProps function for your component, implementing componentWillReceiveProps in your component, and checking to see if specific props from the store have changed.

    There are also a couple addon libraries that try to handle this case: https://github.com/ashaffer/redux-subscribe and https://github.com/jprichardson/redux-watch . Both basically let you specify a specific portion of the state to look at, using different approaches.

提交回复
热议问题