mentalMedley
mentalMedley

Reputation: 76

React Native+Redux: connect trouble

I am quite new to React Native / Redux. Trying to study I wrote simpliest example. But it seems connecting doesn't work. Can anybody explain me why?

My code

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);

Output

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

connect doesn't work. What's wrong with this code?

Upvotes: 0

Views: 418

Answers (1)

mentalMedley
mentalMedley

Reputation: 76

Trouble because of Redux requires to separate presentational and container components. Correct code:

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 creates container AppContainer based on presentation App.

Upvotes: 1

Related Questions