javascript 使用 React 和 redux 从不同的 reducer 调用操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32875518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling an action from a different reducer with React and redux
提问by Mike Boutin
I got 2 components; A market and a status. The status component manage the amount of money the user have and the market have buttons to buy some stuff. When i click on the button (in the market component), i want my money to decrement.
我有 2 个组件;一个市场和一个地位。状态组件管理用户拥有的金额,市场有按钮来购买一些东西。当我点击按钮(在市场组件中)时,我希望我的钱减少。
How can i achieve this the best way possible?
我怎样才能以最好的方式实现这一目标?
This is my App component who has the Market and Status:
这是我的具有市场和状态的应用程序组件:
import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as MarketActions from '../actions/market-actions';
import * as StatusActions from '../actions/status-actions';
import Market from './Market.react';
import Status from './Status.react';
export default class App extends React.Component {
render() {
const { dispatch, market, status } = this.props;
return (
<div>
<h1>App</h1>
<Link to='/'>App</Link>{' '}<Link to='/home'>Home</Link>
<Status status={status} {...bindActionCreators(StatusActions, dispatch)} />
<Market market={market} {...bindActionCreators(MarketActions, dispatch)} {...bindActionCreators(StatusActions, dispatch)} />
{this.props.children}
</div>
);
}
}
export default connect(state => ({ market: state.market, status: state.status }))(App);
I bound the actions from the status on the market component (i feel it's not the right thing to do, but it worked).
我从市场组件的状态绑定了操作(我觉得这不是正确的做法,但它有效)。
After this, i handle these actions in the Market component on a click of a button like this:
在此之后,我通过单击这样的按钮在 Market 组件中处理这些操作:
handleBuyClick(e) {
let { index, price } = e.target.dataset;
index = parseInt(index);
price = parseInt(price);
this.props.buyItem(index);
this.props.changeMoney(price); //this bugs me, i think it don't belongs there
}
Is there a better way?
有没有更好的办法?
Thank you
谢谢
回答by Victor Suzdalev
Why not react on the same action in both reducers? You could have code like this:
为什么不在两个减速器中对相同的动作做出反应?你可以有这样的代码:
function status(state, action){
...
switch(action.type){
case BUY_ITEM: {
return 'bought'
}
}
...
}
function market(state, action){
...
switch(action.type){
case BUY_ITEM: {
return {...state, action.itemId : state[action.itemId] - 1 }
}
}
...
}
With whatever "reaction code" you need to perform.
使用您需要执行的任何“反应代码”。