我如何跟踪在 redux store 中所做的更改

How can I keep track of changes made in redux store

我不想调用 store.subscribe 方法。我只想将商店状态与组件状态同步。 I am trying to make a shopping cart - 有一个组件 CartItems 通过使用映射函数将道具传递给 SingleCartItem 组件来显示 SignleCartItem

每当用户更新数量时,SignleCartItem 都会发送一个操作,商店会保存添加到购物车的商品总数及其价格。

现在的问题是显示购物车项目的小计和总计的组件不会将商店的状态与其状态(显示总计)同步。

让一切变得简单:

One component updates the store state, other component is not syncing it on run time.

PS: 请忽略商品详情:P

如果我的理解正确,你想在你的组件中显示商店状态 'total'。您需要将您的组件连接到商店。 es6中的一个例子:

class SomeComponent extends React.Component{ ... }
const mapStateToProps = state => ({total:state.total});
export default connect(mapStateToProps)(SomeComponent);

关于 redux connect 函数的文档在这里: https://github.com/reactjs/react-redux/blob/master/docs/api.md

如果你想跟踪在 redux store 中所做的更改,就像你在标题中所说的,你可以尝试 redux-logger。您将能够在 google chrome 控制台中看到创建的每个操作以及商店中的每个更改,就像这样

而不是 store.subscribe() 使用 react-redux 将 Redux 与 React 绑定。​​

在您的根组件中,导入您使用 createStore() 创建的商店并将其提供给使用 Provider

的组件
import App from './App.js'
import store from './store/index.js'
import {Provider} from 'react-redux' 

const myApp = () => (
    <Provider store={store}>
        <App />
    </Provider>
);

ReactDOM.render(<myApp />, document.getElementById("root"));

然后,在您想要监听状态的任何组件内,使用 connect 通过将它们映射到 props

来连接您想要在该组件中的状态部分
import {connect} from 'redux-react'

class App extends React.Component {
    render(){
        return (
            <div>
                <h1>{this.props.title}</h1>
            <div>
        )
    }
}

在导出组件之前将状态映射到道具

const mapStateToProps = (state) => {
    title: state.title
}

export default connect(mapStateToProps)(App)