2017-10-04 4 views
0

API에서 데이터를 가져 오는 여러 가지 동작이 내 응용 프로그램에 있습니다. 작업을 가져 오는 경우 내 redux 저장소에 "로드"속성을 설정 중입니다. 이제 앱에서 데이터를 가져 오는 네트워크 표시기를 보여주고 싶습니다. Redux를 사용하여 네트워크 표시기의 가시성을 설정할 위치는?

나는 빠른 & 더러운 해결책을 발견하지만 난이 그것을 할 수있는 방법이 아니라는 것을 확신 :

import React, { Component } from 'react'; 
import { AppRegistry, StatusBar } from 'react-native'; 
import { Provider } from 'react-redux'; 
import { createStore, applyMiddleware } from 'redux'; 
import thunk from 'redux-thunk'; 
import reducer from './app/reducers'; 

import App from './app/providers/App'; 

const createStoreWithMiddleware = applyMiddleware(thunk)(createStore); 
const store = createStoreWithMiddleware(reducer); 

class AppName extends Component { 
    render() { 

     store.subscribe(() => { 
      if( 
       store.getState().dishes.loading 
       || store.getState().deals.loading 
      ) StatusBar.setNetworkActivityIndicatorVisible(true); 
      else StatusBar.setNetworkActivityIndicatorVisible(false); 
     }); 


     return (
      <Provider store={store}> 
       <App /> 
      </Provider> 
     ); 
    } 
} 

AppRegistry.registerComponent('AppName',() => AppName); 

이러한 청취자 후크하는 올바른 방법은 무엇입니까가?

답변

1

StatusBar.setNetworkActivityIndicatorVisible 번을 너무 많이 호출하지 않으려면 연결된 구성 요소에서 componentWillReceiveProps을 사용하여 주에서 변경 사항을 볼 수 있습니다.

import AppContainer from './containers/AppContainer'; 

class AppName extends Component { 
    render() {   
     return (
      <Provider store={store}> 
       <AppContainer /> 
      </Provider> 
     ); 
    } 
} 

용기/AppContainer.js

import App from '../components/App.js'; 

const mapStateToProps = state => ({ 
    loading: state.dishes.loading || state.deals.loading 
}); 

export default connect(mapStateToProps)(App); 

부품/App.js

class App extends Component { 

    componentWillReceiveProps(nextProps) { 
    if (!this.props.loading && nextProps.loading) { 
     // Changing from `not loading` to `loading` 
     StatusBar.setNetworkActivityIndicatorVisible(true); 
    } else if (this.props.loading && !nextProps.loading) { 
     // Changing from `loading` to `not loading` 
     StatusBar.setNetworkActivityIndicatorVisible(false); 
    } 
    } 

    // ... 
} 
관련 문제