2017-06-13 41 views
0

React Native/Reduxにはかなり新しくなっています。勉強しようとすると、私は簡単な例を書いた。しかし、接続がうまくいかないようです。なぜ誰かが私に説明できますか?React Native + Redux:connect trouble

私のコード

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

function reducer(state, action) { 
    if(state === undefined) 
    return { 
     age: 31 
    }; 

    return state; 
} 

var store = createStore(reducer); 

const App = (props) => { 
    return (
    <View> 
     <Text>Store: { JSON.stringify(store.getState()) }</Text> 
     <Text>Props: { JSON.stringify(props) }</Text> 
    </View> 
); 
} 

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

function mapStateToProps(state) { 
    return { 
    age: state.age 
    } 
} 
export default connect(
    mapStateToProps 
)(App); 

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

出力

Store: {"age":31} 
Props: {} 

は動作しません接続します。このコードで何が問題になっていますか?

答えて

0

Reduxに起因する問題は、プレゼンテーションコンポーネントとコンテナコンポーネントを分離する必要があります。正しいコード:

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

function reducer(state, action) { 
    if(state === undefined) 
     return { 
      age: 31 
     }; 

    return state; 
} 

var store = createStore(reducer); 

const App = (props) => { 
    return (
     <View> 
      <Text>Store: { JSON.stringify(store.getState()) }</Text> 
      <Text>Props: { JSON.stringify(props) }</Text> 
     </View> 
    ); 
} 

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

function mapStateToProps(state) { 
    return { 
     age: state.age 
    } 
} 
var AppContainer = connect(
    mapStateToProps 
)(App); 

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

connectがプレゼンテーションAppに基づいてコンテナAppContainerを作成します。