2017-06-13 214 views
0

我是React Native/Redux的新手。試圖研究我寫的最簡單的例子。但似乎連接不起作用。有人可以解釋我爲什麼嗎?React Native + 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}> 
     <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