React Native + Redux:连接麻烦

时间:2017-06-13 03:39:06

标签: javascript 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: {}

连接不起作用。这段代码有什么问题?

1 个答案:

答案 0 :(得分:1)

由于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根据演示文稿AppContainer创建容器App