通过从非反应组件分派动作来更新反应组件 [英] 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.
我在 React.js 中构建了网站的某些部分 - 比如购物车、购物车按钮等.
I have build parts of the site in React.js - like the cart, the cart button etc.
configureStore.js:
export default function configureStore(initialState) {
const store = createStore(
reducers,
initialState
return store
}
行动:
export function updateCart(payload) {
return {
type: CART_UPDATE,
payload: payload
}
}
减速器:
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
... componnent etc.
function mapStateToProps(state) {
return {
cart: state.cart.data
};
}
export default connect(mapStateToProps)(CartButton);
供应商
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();
然后..
store.dispatch(updateCart(response));
动作被调度并且状态被更新.购物车按钮组件通过连接.react-redux connect() 函数.但不知何故,它没有使用新数量更新组件.
The action is dispatched and the state is updated. The cart-button component is connected via. react-redux connect() function. But somehow it isn't updating the component with the new quantity.
当我从购物车 React 组件中分派一个动作时,它工作正常.
When I dispatch an action from within my cart React component it works fine.
我可能遗漏了一些明显的东西.有什么建议吗?
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.
我只是从我的根 app.js 文件中导入了 store 常量,如下所示:
I simply imported the store constant from my root app.js-file like this:
从'./app'导入{商店};
import { store } from './app';
这篇关于通过从非反应组件分派动作来更新反应组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!