【问题标题】:React Functional Component not rendering反应功能组件不呈现
【发布时间】: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


    【解决方案1】:

    您需要返回您在errorloading 案例中创建的组件。

      if (error) 
        return (<View><Text>Error</Text></View>)
      else if (loading)
        return (<ActivityIndicator size='large' />)
      else 
        return (<SafeAreaView
      ...
    

    编码模式

    {error &&
          <View><Text>Error</Text></View>
        }
    

    您在代码中拥有的内容只能在 JSX 组件内用于有条件地呈现另一个组件。例如

    <OuterComponent>
      {flag && (<OptionalComponent/>)}
    </OuterComponent>
    

    之所以有效,是因为 JSX 中的花括号包含常规 JavaScript 代码,flag &amp;&amp; (&lt;OptionalComponent/&gt;) 的结果要么是 false 要么是 &lt;OptionalComponent&gt;,而对于 React,false 根本不会生成任何输出。

    【讨论】:

    • 抛出错误:Cannot read property 'instruments' of undefined
    • 我假设这是因为您没有成功从您的 fetch 中获取数据。您可能应该对返回的承诺进行一些拒绝处理。
    猜你喜欢
    • 2023-03-29
    • 2023-01-31
    • 2021-02-27
    • 2017-05-12
    • 1970-01-01
    • 2017-08-24
    • 2018-07-28
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多