Состояние Redux возвращает значение по умолчанию в useEffect - PullRequest
0 голосов
/ 04 мая 2020

У меня проблемы с созданием кошелька bitcoin с React Native. Когда я использую диспетчеризацию в useEffect, на странице отображается правильное значение, но если я добавляю console.log (balanceBt c), он возвращает 0. Вот почему также balanceUsd всегда равно 0. Кажется, что dispatch () устанавливает правильное значение значение для balanceBt c на секунду и внезапно сбросить его до начального значения. Кто-нибудь может мне помочь? Спасибо.

Я поставил случайный адрес на сумму 0,0006 бит c по запросу API.

MainApplication. js:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Text, View, StatusBar, StyleSheet, ImageBackground, FlatList, RefreshControl, ScrollView } from 'react-native';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import { NavigationContainer } from '@react-navigation/native';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import { Divider } from 'react-native-paper';
import { useSelector, useDispatch } from 'react-redux';
import {setBalanceUsd, setBalanceBtc, setResults, setConversion} from '../../actions';

const apikey = "_______________________________";

/*WALLET PAGE*/
export default function wallet() {
const dispatch = useDispatch();

  const address = useSelector(state => state.address);
  const balanceBtc = useSelector(state => state.balanceBtc);
  const balanceUsd = useSelector(state => state.balanceUsd);
  const results = useSelector(state => state.results);
  const conversion = useSelector(state => state.conversion);

  const setBtc = (response) => {
                                  dispatch(setBalanceBtc(response.data.payload.balance));
  }

  const setUsd = (response) => {
                                  console.log(balanceBtc);
                                  dispatch(setConversion(response.data.data.amount));
                                  dispatch(setBalanceUsd(conversion*balanceBtc));
  }
  const setTransactions = (response) => {
                                  dispatch(setResults(response.data.payload));
  }
  isMounted = true;

  useEffect(() => {
                   if(isMounted){
                   const fetchBalanceBtc = async () => {
                        const response = await axios.get("https://api.cryptoapis.io/v1/bc/btc/mainnet/address/bc1q8g4ye9qspsjmej4r777aqxuakwlh4vjzp7mvg9",
                                                        {headers: {"Content-Type": "application/json" , "X-API-Key": apikey}});
                            setBtc(response);
                   };
                   fetchBalanceBtc();

                   const fetchBalanceUsd = async () => {
                        const response = await axios.get("https://api.coinbase.com/v2/prices/spot?currency=USD");
                        if (isMounted){
                            setUsd(response);
                        }
                   };
                   fetchBalanceUsd();

                   const fetchTransactions = async () => {
                        const resp = await axios.get("https://api.cryptoapis.io/v1/bc/btc/mainnet/address/3P63HCj9fFwXgHB6xzWvGEYkKBfzXjgw2p/basic/transactions" ,
                                                        {headers: {"Content-Type": "application/json" , "X-API-Key": apikey}});
                        if (isMounted){
                            setTransactions(resp);
                        }
                   };
                   fetchTransactions();

                   return () => {
                        isMounted = false;
                   };}
  }, [isMounted]);



  return (
        <View style={{flex: 1 }}>
            {/*SET IMAGE AS WHOLE PAGE BACKGROUND*/}
            <ImageBackground source={{ uri: "https://superdevresources.com/wp-content/uploads/2016/02/5-backgrounds.jpg" }} style={styles.image}>
            {/*TITLE*/}
            <View style={{flex: 1, justifyContent: "center", }}>
                <Text style={styles.yourWallet}>Your wallet:</Text>
            </View>
            {/*BALANCE SECTION*/}
            <View style={{flex: 4}}>
                <Text style={styles.actualBalance}>Actual balance:</Text>
                <Text style={styles.btcBalance}>{balanceBtc} BTC</Text>
                <Text style={styles.usdBalance}>{balanceUsd}$</Text>
            </View>
            {/*RECENT TRANSACTION TITLE*/}
            <View style={{flex: 1, flexDirection: "column-reverse", borderTopLeftRadius: 30, borderTopRightRadius: 30, backgroundColor: "rgba(232, 225, 225, 0.9)"}}>
                <Text style={styles.recentTransaction}>Recent transaction:</Text>
            </View>
            {/*TRANSACTION*/}
            <View style={{flex: 4, backgroundColor: "rgba(232, 225, 225, 0.9)"}}>
                {(results === []) ?
                (<Text style={{textAlign: "center", fontFamily: "FontAwesome5_Regular"}}>No recent transactions!</Text>) :(
                    <FlatList
                        data = {results}
                        renderItem={({item}) => {{item.sent.address === undefined ? (
                                        <React.Fragment>
                                        <View style={{flexDirection:"row"}}>
                                            <View style={{justifyContent: "center", paddingLeft: 20}}>
                                                <FontAwesome5 name="sort-up" color="green" size={23} />
                                            </View>
                                            <View style={{flexDirection: "column", flex:1, paddingRight: 15}}>
                                                <View style={{flexDirection: "row", justifyContent: "space-between", paddingLeft: 15}}>
                                                    <View>
                                                        <Text style={styles.from}>Id:</Text>
                                                    </View>
                                                    <View>
                                                        <Text style={{fontSize: 15}}>{item.txid}</Text>
                                                    </View>
                                                </View>
                                                <View style={{flexDirection: "row", justifyContent: "space-between", paddingLeft: 15}}>
                                                    <View>keyExtractor={(item, index) => index.toString()}
                                                        <Text style={styles.from}>Amount:</Text>
                                                    </View>
                                                    <View>
                                                        <Text style={{fontSize: 15}}>{item.amount} BTC</Text>
                                                    </View>
                                                </View>
                                            </View>
                                        </View>
                                        <View style={{alignItems: "center", marginTop: 6, marginBottom: 6}}><Divider style={{width: 360, paddingTop: 2}}/></View>
                                        </React.Fragment>
                                        ) : (
                                        <React.Fragment>
                                        <View style={{flexDirection:"row"}}>
                                            <View style={{justifyContent: "center", paddingLeft: 20}}>
                                                <FontAwesome5 name="sort-down" color="green" size={23} />
                                            </View>
                                            <View style={{flexDirection: "column", flex:1, paddingRight: 15}}>
                                                <View style={{flexDirection: "row", justifyContent: "space-between", paddingLeft: 15}}>
                                                    <View>
                                                        <Text style={styles.from}>Id:</Text>
                                                    </View>
                                                    <View>
                                                        <Text style={{fontSize: 15}}>{item.txid}</Text>
                                                    </View>
                                                </View>
                                                <View style={{flexDirection: "row", justifyContent: "space-between", paddingLeft: 15}}>
                                                    <View>
                                                        <Text style={styles.from}>Amount:</Text>
                                                    </View>
                                                    <View>
                                                        <Text style={{fontSize: 15}}>{item.amount} BTC</Text>
                                                    </View>
                                                </View>
                                            </View>
                                        </View>
                                        <View style={{alignItems: "center", marginTop: 6, marginBottom: 6}}><Divider style={{width: 360, paddingTop: 2}}/></View>
                                        </React.Fragment>
                                        )}}}
                                        keyExtractor={(item, index) => index.toString()}
                    />)}
            </View>

            </ImageBackground>
        </View>
  );
}

const styles = StyleSheet.create({
    yourWallet: {
        backgroundColor: "rgba(105, 79, 173, 0.75);",
        marginLeft: 20,
        paddingTop: 5,
        paddingBottom: 5,
        borderRadius: 15,
        width: 200,
        textAlign: "center",
        color: "#fff",
        fontSize: 35,
        fontFamily: "FontAwesome5_Regular",
    },
    actualBalance: {
        color: "#dcdcdc",
        fontSize: 25,
        paddingBottom: 5,
        paddingTop: 5,
        fontFamily: 'FontAwesome5_Regular',
        paddingLeft: 35,

    },
    btcBalance: {
        color: "#fff",
        fontSize: 30,
        fontFamily: 'FontAwesome5_Brands',
        paddingBottom: 5,
        paddingLeft: 35,
    },
    usdBalance: {
        textAlign: "center",
        width: 100,
        borderRadius: 5,
        backgroundColor: "rgba(220,220,220,0.8)",
        fontSize: 22,
        fontFamily: 'FontAwesome5_Brands',
        marginLeft: 35,
    },
    recentTransaction: {
        color: "#999da0",
        fontSize: 25,
        paddingLeft: 35,
        paddingBottom: 10,
        fontFamily: 'FontAwesome5_Brands',
    },
    from: {
        fontSize: 16,
        fontFamily: 'FontAwesome5_Solid',
    },
    image: {
        flex: 1,
    }
  }
);

. / Redurs /setBalanceBtc.js:

const setBalanceBtcReducer = (state = 0, action) => {
    switch(action.type){
        case 'SETBALANCEBTC':
            return action.payload;
        default:
            return state;
    }
};

export default setBalanceBtcReducer;

. / redurs / index. js:

import setAddressReducer from './setAddress';
import setPrivateKeyReducer from './setPublicKey';
import setPublicKeyReducer from './setPrivateKey';
import setBalanceBtcReducer from './setBalanceBtc';
import setBalanceUsdReducer from './setBalanceUsd';
import setResultsReducer from './setResults';
import setConversionReducer from './setConversion';
import {combineReducers} from 'redux';

const allReducers = combineReducers({
    address: setAddressReducer,
    publicKey: setPublicKeyReducer,
    privateKey: setPrivateKeyReducer,
    balanceBtc: setBalanceBtcReducer,
    balanceUsd: setBalanceUsdReducer,
    results: setResultsReducer,
    conversion: setConversionReducer,
});

export default allReducers;

. / actions / index. js:

export const setAddress = (e) => {
    return{
        type: 'SETADDRESS',
        payload: e
    }
}
export const setPrivateKey = (e) => {
    return{
        type: 'SETPRIVATEKEY',
        payload: e
    }
}
export const setPublicKey = (e) => {
    return{
        type: 'SETPUBLICKEY',
        payload: e
    }
}
export const setBalanceBtc = (e) => {
    return{
        type: 'SETBALANCEBTC',
        payload: e
    }
}
export const setBalanceUsd = (e) => {
    return{
        type: 'SETBALANCEUSD',
        payload: e
    }
}
export const setResults = (e) => {
    return{
        type: 'SETRESULTS',
        payload: e
    }
}
export const setConversion = (e) => {
    return{
        type: 'SETCONVERSION',
        payload: e
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...