2017-11-09 10 views
0

하나의 화면에서 균형을 업데이트 할 때 redux를 구현하여 여러 화면에서 균형을 유지하려고합니다. 다른 모든 화면/구성 요소에 반영되어야합니다.반응식 네이티브의 Redux 오류

나는 꽤 새로운 편이다. 당신이 redux 주변의 복잡성을 알고 있기 때문에 심지어 그것을 구현하기 어렵게 만듭니다.

나는 GitHub 및 youtube에서 몇 가지 예를 따라 그것을 구현하기 시작했습니다.

아래 작업 폴더 있습니다. 다음 두 파일

counteractions.js

기어 folder.I에서
import * as types from './actionTypes.js'; 

//ActionCreator methods 

export function updateBalance(balanceInfo) { 

    return { 
     type: types.LEDGER_BALANCE, 
     payLoad: { balanceInfo } 
    } 
} 

는이 파일이

balance.js ConfigureStore.js

수입 {createStore에서

import * as types from '../actions/actionTypes.js'; 

const initialState = { 
    balance: 0 
} 

// reducer functions .. accepts current/initial state , actions and returns new state 

const balanceReducer=(state,action)=> 
{ 
    switch (action.type) { 
     case types.LEDGER_BALANCE: 
      return { 
       balance: action.payload.balanceInfo 
      } 
      break; 
     default: 
      break; 
    } 
} 

export default balanceReducer; 

}에서 'redux'; './reducers/index.js'에서 가져온 rootReducer;

import balanceReducer from './reducers/balance.js'; 

const initailState = { 
    balance: 0, 
} 

export const store=createStore(balanceReducer,balanceReducer); 

App.js

/** 
* Sample React Native App 
* https://github.com/facebook/react-native 
* @flow 
*/ 

import React, { Component } from 'react'; 
import { Provider } from 'react-redux'; 
//Provider - makes redux store available to connect() class in component hierarchy below 
import { applyMiddleware, createStore, compose, combineReducers } from "redux"; 
import thunkMiddleware from 'redux-thunk'; 
import createLogger from 'redux-logger'; 
import rootReducer from './reducers/index.js'; 
//import store from './configureStore.js'; 

import { 
    Platform, 
    StyleSheet, 
    Text, 
    View, 
    TouchableOpacity, 
    TextInput 
} from 'react-native'; 
import ReduxDemo from "./reduxDemo.js"; 
import { store, reducer } from './balanceDemo.js'; 

const instructions = Platform.select({ 
    ios: 'Press Cmd+R to reload,\n' + 
    'Cmd+D or shake for dev menu', 
    android: 'Double tap R on your keyboard to reload,\n' + 
    'Shake or press menu button for dev menu', 
}); 

export default class App extends Component<{}> { 

    constructor(props) { 
    super(props); 
    this.state = { 
     balancelocal: '', 
    } 
    } 



    _updateLedger =() => { 
    // store.dispatch({ type: 'BALANCE', payLoad: '500' }); 
    store.dispatch({ type: 'BALANCE', payLoad: 'Your balance is 8000 MUR' }); 
    } 


    render() { 

    store.subscribe(() => { 

     this.setState({ 
     balancelocal: store.getState(), 
     }) 
     //this.balanceInfo = store.getState().balance; 
    // alert(this.state.balancelocal); 
    }); 
    return (
     <View style={styles.container}> 
     <TouchableOpacity onPress={this._updateLedger}> 
      <Text>Update balance</Text> 
     </TouchableOpacity> 

     <TextInput style={{height:100,width:400}} value={this.state.balancelocal}/> 
     </View> 
    ); 
    } 
} 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center', 
    backgroundColor: '#F5FCFF', 
    }, 
    welcome: { 
    fontSize: 20, 
    textAlign: 'center', 
    margin: 10, 
    }, 
    instructions: { 
    textAlign: 'center', 
    color: '#333333', 
    marginBottom: 5, 
    }, 
}); 

나는 구성 저장소 파일을 완료하는 데 아직입니다. 과. 궁금하네요. 어디에서 구독하고 조치를 파견해야합니까?

버튼을 클릭하여 균형을 업데이트하고 싶습니다. app.js 있습니다. 자동으로 다른 페이지의 잔액을 업데이트하십시오 ..

redux를 이해하고 구현하도록 안내해주십시오. 더 나은 폴더 구조와 redux 구현 방법을 제안하십시오.

답변

0

여기 이해하기 쉽습니다.

기본 워크 플로우는

Component Button > Action > Reducer > Component Props > Render 

당신이 상점의 설치 및 REDUX를 통해 "이벤트"의 호출이 모두 필요이를 위해 (당신은 다른 것과 수신 구성 요소를 가질 수있다).

아래 예는 완벽하지는 않지만 여기에 입력 한 예입니다.하지만 다른 구성 요소가 동작에서 값을 얻는 방법은 이 '연결'HOC을 사용하기 때문입니다. 때마다 redux는 '연결'된 모든 구성 요소를 호출하는 상태 변경을 가져옵니다. 여기서는 업데이트 된 균형을 가져 와서 'mapStateToProps'함수의 일부로 반환합니다.이 함수는 해당 객체로 구성 요소 소품을 설정하는 것입니다. 저울은 this.props.balance을 통해 액세스하여 표시됩니다.

이것은 액션에서 API를 호출하고 결과를 감속기에 저장하려는 경우에 유용합니다. 연결된 모든 구성 요소는 새 데이터를 가져옵니다.

주 1 : 나는 미사용 redux-thunk을 사용하여 파견하므로 용서할 수 없습니다.

주 2 : 이것은 간단한 예입니다. 앱이 좋아지면 감속기 변경으로 인해 연결된 모든 구성 요소가 호출되므로 오버 렌더링을 방지해야합니다. 여기서 reselect을 사용합니다.

설정

reducers.js

import { combineReducers } from 'redux'; 
import { balanceReducer } from 'balanceReducer'; 
export default combineReducers({ 
    balanceReducer 
}) 

store.js

import { createStore, applyMiddleware } from 'redux'; 
import thunk from 'redux-thunk' 

import combineReducers from './reducers' 

export default function configureStore() { 
    let store = createStore(combineReducers, applyMiddleware(thunk)); 
    return store; 
} 

하는 index.js

import React, { Component } from 'react'; 
import { AppRegistry, View } from 'react-native'; 
import { Provider } from 'react-redux'; 

import configureStore from './store'; 
import Component1 from './component1'; 

const store = configureStore() 

const myapp =() => (
    <Provider store={store}> 
    <View> 
     <Component1 /> 
    <View> 
    </Provider> 
) 

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

구성 요소

component1.js (키 부분은 연결 HOC입니다)

import { connect } from 'react-redux'; 
import React, { Component } from 'react'; 
import { Text, View, TouchableOpacity } from 'react-native'; 
import { updateBalance } from './action'; 

class Component1 extends Component { 

    _updateLedger =() => { 
     this.props.updateBalance(500); 
    } 
    render() { 
     const { balance } = this.props; 
     return (
      <View> 
      <TouchableOpacity onPress={this._updateLedger}> 
       <Text>Update balance</Text> 
      </TouchableOpacity> 
      <Text>{balance}</Text> 
      </View> 
     ) 
    } 
} 

function mapStateToProps(state) { 
    return { 
     balance: state.balanceReducer.balance 
    } 
} 

function mapDispatchToProps(dispatch) { 
    return { 
     updateBalance = (balanceInfo) => dispatch(updateBalance(balanceInfo)) 
    }; 
} 

export default connect(
    mapStatetoProps, 
    mapDispatchToProps 
)(Component1) 

는 (여기에서 중요한 부분 새로운 상태를 반환하는 것입니다)

export function updateBalance(balanceInfo) { 

    return { 
     type: types.LEDGER_BALANCE, 
     payLoad: { balanceInfo } 
    } 
} 

balanceReducer.js을 action.js

const initialState = { 
    balance: 0, 
} 
export function balanceReducer(state = initialState, action) { 
    if(action.type === types.LEDGER_BALANCE) { 
     return { 
      balance: action.payLoad.balanceInfo 
     } 
    } 
}