简体   繁体   English

通过从非反应组件调度操作来更新React组件

[英]Update React component by dispatching action from non-react component

I'm trying to update the cart-button on a project when the user adds an item to the cart. 当用户将项目添加到购物车时,我正在尝试更新项目上的购物车按钮。

I have build parts of the site in React.js - like the cart, the cart button etc. 我在React.js中构建了网站的一部分 - 比如购物车,购物车按钮等。

configureStore.js: configureStore.js:

export default function configureStore(initialState) {
      const store = createStore(
        reducers,
        initialState
      return store
    }

Action: 行动:

export function updateCart(payload) {
    return {
        type: CART_UPDATE,
        payload: payload
    }
}

Reducer: 减速器:

export default function cart(state = {}, action) {

    switch (action.type) {

            case CART_UPDATE:

            const   cart = {
                        data: action.payload.cart,
                        errors: action.payload.errors,
                        isFetching: false
                    };

            return {
                ...state,
                ...cart
            };

    return state;
}

CartButton.js CartButton.js

... componnent etc.

function mapStateToProps(state) {
    return {
        cart: state.cart.data
    };
}

export default connect(mapStateToProps)(CartButton);

Provider 提供商

import configureStore from './store/configureStore'
var store = configureStore();

ReactDOM.render((<Provider store={store}><Cart showControls={true} /></Provider>), document.getElementById('react-cart'));

I'm dispatching an action that is supposed to update the cart quantity from a non-react component like this: 我正在调度一个应该从非反应组件更新购物车数量的操作,如下所示:

// imports 
import { dispatch } from 'redux';
import { updateCart } from '../../actions/cart_actions';
import configureStore from '../../store/configureStore'
var store = configureStore();

and then.. 接着..

store.dispatch(updateCart(response));

The action is dispatched and the state is updated . 调度操作更新状态 The cart-button component is connected via. 推车按钮组件通过连接。 react-redux connect() function. react-redux connect()函数。 But somehow it isn't updating the component with the new quantity. 但不知何故,它没有使用新数量更新组件。

When I dispatch an action from within my cart React component it works fine. 当我从我的购物车React组件中发出一个动作时,它工作正常。

I might be missing something obvious. 我可能会遗漏一些明显的东西。 Any suggestions? 有什么建议么?

So what I ended up figuring out is that you shouldn't define your store in more than one place. 所以我最终弄清楚的是,你不应该在多个地方定义你的商店。

I simply imported the store constant from my root app.js-file like this: 我只是从我的root app.js文件中导入了商店常量,如下所示:

import { store } from './app'; 从'./app'导入{store};

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

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