我有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
}
有更好的方法吗?
谢谢
答案 0 :(得分:30)
为什么不对两个减速器中的相同动作做出反应?你可以有这样的代码:
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 }
}
}
...
}
用任何&#34;反应代码&#34;你需要表演。