20

我有 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
}

有没有更好的办法?

谢谢

4

1 回答 1

31

为什么不对两个减速器中的相同动作做出反应?你可以有这样的代码:

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 }
        }
    }
...
}

使用您需要执行的任何“反应代码”。

于 2015-10-03T13:03:23.947 回答