从redux获得多个状态的反应原生

时间:2018-05-20 17:23:50

标签: reactjs react-native redux redux-thunk

我要创建一个应用程序来显示前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);

1 个答案:

答案 0 :(得分:2)

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

将您的减速机更改为:

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