使用 React 和 redux 从不同的 reducer 调用一个动作

Calling an action from a different reducer with React and redux

我有 2 个组件;一个市场,一种地位。状态组件管理用户拥有的钱数,市场上有按钮可以购买一些东西。当我点击按钮(在市场组件中)时,我希望我的钱减少。

我怎样才能以最好的方式实现这一目标?

这是我的具有市场和状态的 App 组件:

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);

我从市场组件的状态中绑定了操作(我觉得这不是正确的做法,但它奏效了)。

在此之后,我通过单击按钮在市场组件中处理这些操作,如下所示:

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

无论"reaction code"你需要做什么。