簡體   English   中英

使用React和redux從不同的reducer調用一個動作

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM