【发布时间】:2020-12-11 21:34:12
【问题描述】:
我的反应原生应用程序在运行后显示空白屏幕 使用 redux 进行状态管理。 HomeScreen 功能组件也可能无法正确呈现平面列表。
也许我错误地使用了 useSelector 钩子,或者 Redux 操作不正确。导航由反应导航处理。
import {
GET_CURRENCY,
GET_CURRENCY_SUCCESS,
GET_CURRENCY_FAILURE
} from "../ActionTypes";
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "{BearerToken} ");
const requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
export const getCurrency = () =>{
return{
type: GET_CURRENCY,
}
}
export const currencySuccess = instruments => {
return{
type: GET_CURRENCY_SUCCESS,
payload: instruments
}}
export const currencyFailure = error => {
return{
type: GET_CURRENCY_FAILURE,
payload:
error
}
}
export const fetchCurrency =() => {
return dispatch => {
dispatch(getCurrency())
fetch("https://api-fxpractice.oanda.com/v3/instruments/EUR_USD/candles?price=M", requestOptions)
// eslint-disable-next-line no-unused-vars
.then(response => response.data)
.then(instruments =>{
dispatch (currencySuccess(instruments))
})
// eslint-disable-next-line no-undef
.catch (error => {
const errorMsg = error.message
dispatch(currencyFailure(errorMsg))
})
}
}
export default fetchCurrency
主屏幕
import React, {useEffect} from 'react'
import { FlatList, ActivityIndicator, View, Text, SafeAreaView} from 'react-native'
import Instrument from '../../../components/Instrument'
import styles from './styles'
import {useSelector, useDispatch} from 'react-redux'
import fetchCurrency from '../../Redux/Actions/currencyActions'
function HomeScreen () {
const dispatch = useDispatch()
useEffect(() => {
dispatch(fetchCurrency())
}, []);
const { instruments, loading, error} = useSelector(state => state.reducer
);
{error &&
<View><Text>Error</Text></View>
}
{loading && <ActivityIndicator size='large' />}
return(
<SafeAreaView
style={styles.container}
>
<FlatList
data={instruments}
numColumns={1}
contentContainerStyle = {styles.list}
keyExtractor = {({item}) => item.toString() }
renderItem = {(item, index) => (
<Instrument currency={item} />
)}
/>
</SafeAreaView>
);
}
export default HomeScreen
减速器
import {
GET_CURRENCY,
GET_CURRENCY_SUCCESS,
GET_CURRENCY_FAILURE
} from '../ActionTypes'
const initialState = {
instruments: [],
loading: false,
error: null
}
const reducer = (state= initialState, action) => {
switch(action.type){
case GET_CURRENCY:
return {...state, loading: true}
case GET_CURRENCY_SUCCESS:
return {...state, loading: false, instruments: action.payload.instruments }
case GET_CURRENCY_FAILURE:
return { ...state, loading: false, error: action.payload}
default:
return state
}
}
export default reducer;
【问题讨论】:
标签: reactjs react-native redux react-redux