首页 > 解决方案 > 在 react native 中从 redux 获取多个状态

问题描述

我将创建一个应用程序来显示前 5 种加密货币的价格。我创建了一个硬币列表并将其传递给 FlatList,每张卡片都是特定的硬币详细信息。但在我的实现中,所有卡都显示相同的价格,这是可以预期的,因为我只有单一的价格。感谢您对此事的任何想法帮助。

coinReducer.js

const INITIAL_STATE = {
  price: '',
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case COIN_PRICE:
      return { ...state, price: action.payload };
    default:
      return state;
  }
};

coinAction.js

const URL = 'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH,XRP,BCH,EOS&tsyms=USD';

export const getCoinPrice = (symbol) => async (dispatch) => {
  try {
    const response = await axios.get(URL);
    return dispatch({
      type: COIN_PRICE,
      payload: response.data.RAW[symbol].USD.PRICE,
    });
  } catch (error) {
    throw error;
 }
};

cardSection.js

class Card extends Component {

  componentWillMount() {
    this.props.getCoinPrice(this.props.item.symbol);
  }

  render() {
    return (
      <View>
        <Text>
          this.props.price
        </Text>
      </View>
    )
  }
}

export default connect(state => ({
  price: state.coinPrice.price
}), { getCoinPrice })(Card);

标签: reactjsreact-nativereduxredux-thunk

解决方案


我认为您可以将所有货币的价格保留在商店中,而不是每次都只获取和更新其中一个。

将减速器更改为:

const INITIAL_STATE = {
  price: {},
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case COIN_PRICE:
      return { ...state, price: { ...state.price, action.payload } };
    default:
      return state;
  }
};

然后将动作更改为

const URL = 'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH,XRP,BCH,EOS&tsyms=USD';
export const getCoinPrice = (symbol) => async (dispatch) => {
  try {
    const response = await axios.get(URL);
    const payload = {};
    payload[symbol] = response.data.RAW[symbol].USD.PRICE;
    return dispatch({
      type: COIN_PRICE,
      payload,
    });
  } catch (error) {
    throw error;
 }
};

最后你的组件变成:

class Card extends Component {

  componentWillMount() {
    this.props.getCoinPrice(this.props.item.symbol);
  }

  render() {
    return (
      <View>
        <Text>
          {this.props.price[this.props.item.symbol]}
        </Text>
      </View>
    )
  }
}

export default connect(state => ({
  price: state.coinPrice.price
}), { getCoinPrice })(Card);

推荐阅读