react-native / redux - 行动不起作用?

时间:2017-03-23 22:21:27

标签: react-native redux

我正在使用react-native / redux并且正在调度一个应该显示数字的动作但是会抛出错误:

  

未处理的JS异常:对象作为React子对象无效(找到:   具有键{type,payload}的对象。如果你想渲染一个集合   对于子级,使用数组或使用包装对象   来自React附加组件的createFragment(对象)。检查渲染方法   Text

createStore.js

import { createStore, applyMiddleware, combineReducers } from 'redux';
import createLogger from 'redux-logger';
import numReducer from './reducers/numReducer';

const logger = createLogger();

export default (initialState = {}) => (
  createStore(
    combineReducers({
      numbers: numReducer
    }),
    initialState,
    applyMiddleware(logger)
  )
);

App.js

import React from 'react';
import { Provider } from 'react-redux';
import HomeScreen from './components/HomeScreen';
import createStore from './createStore';

const store = createStore();

export default () => (
  <Provider store={store}>
    <HomeScreen />
  </Provider>
);

numReducer.js

import { LIST_NUMBERS, PICK_NUMBER } from '../actions/actionTypes';

export default (state = [], action = {}) => {
  switch (action.type) {
    case LIST_NUMBERS:
      return action.payload || [];
    case PICK_NUMBER:
      return action.payload;
    default:
      return state;
  }
};

HomeScreen.js

import React from 'react';
import { View } from 'react-native';
import NavContainer from '../containers/NavContainer';


const HomeScreen = () => (
  <View>
    <NavContainer />
  </View>
);

export default HomeScreen;

NavContainer.js

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import { listNumbers, pickNumber } from '../actions/numberActions';

import Nav from '../components/Nav';

const mapStateToProps = state => ({
  numbers: state.numbers
});

const mapDispatchToProps = dispatch => (
  bindActionCreators({
    listNumbers,
    pickNumber
  }, dispatch)
);

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Nav);

Nav.js

import React, { Component, PropTypes } from 'react';
import { View, Text } from 'react-native';


export default class Nav extends Component {

  render() {
    return (
      <View>
        <Text>FirstLine</Text>
        <Text>SecondLind</Text>
        <Text>Number: {this.props.pickNumber(3)}</Text>
      </View>
    );
  }

}

请告知我做错了什么。谢谢

1 个答案:

答案 0 :(得分:1)

您需要从一个生命周期方法或某个处理程序中调度您的操作,然后使用组件中redux存储中的(更新的)道具。

示例:

import React, { Component, PropTypes } from 'react';
import { View, Text } from 'react-native';


export default class Nav extends Component {
  componentDidMount() {
    this.props.pickNumber(3);
  }
  render() {
    return (
      <View>
        <Text>FirstLine</Text>
        <Text>SecondLind</Text>
        <Text>Number: {this.props.numbers}</Text>
      </View>
    );
  }

}