[英]Calling an action from a different reducer with React and redux
我有2个组件; 市场和地位。 状态组件管理用户拥有的金额,市场有按钮购买一些东西。 当我点击按钮(在市场组件中)时,我希望我的钱减少。
我怎样才能以最好的方式实现这一目标?
这是我的应用程序组件,具有市场和状态:
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);
我将行动与市场组件的状态联系起来(我认为这不是正确的事情,但它有效)。
在此之后,我点击按钮就可以在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
}
有没有更好的办法?
谢谢
为什么不对两个减速器中的相同动作做出反应? 你可以有这样的代码:
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 }
}
}
...
}
无论您需要执行什么“反应代码”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.