reactjs - 在 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);
解决方案
我认为您可以将所有货币的价格保留在商店中,而不是每次都只获取和更新其中一个。
将减速器更改为:
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);
推荐阅读
- postgresql - 从 PostgeSQL 中的 JSONB 数组中删除元素
- pandas - 你如何在 Pandas 中使用条件语句进行分组和聚合?
- javascript - TypeError: undefined is not an object (评估 'modules[moduleId].call')
- expo - 如何在博览会中更改自定义字体
- r - 季度同比变化
- android - android 发布变体的颤振 url_launcher 插件问题
- python - 机器学习中的新标签预测
- c - 32 位结构如何表示负 64 位值?
- javascript - chart.js 和异步加载
- python - locust 从摘要报告中删除预期错误 trans (401)