无法连接mapDispatchToProps

时间:2017-08-25 18:21:37

标签: reactjs react-native redux react-redux

如何从我的组件中将action传递给reducer

我的代码:

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

class MyApp extends Component {
    render(){
      return(
        <View>
          <Text> {this.props.dataReducer.name} </Text>
          <Button
            onPress={this.props.setName('newName')}
            title="Click to change Name"
            color="blue"
          />
        </View> 
        );
    }
}

function mapStateToProps (state) {
  return {
    dataReducer: state.dataReducer
  };
};

function mapDispatchToProps (dispatch) {
  return {
    setName: (name) => {
      dispatch({
        type: "SET_NAME",
        payload: name
      })
    }
  };
};


export default connect( mapStateToProps, mapDispatchToProps )( MyApp )

dataReducer

const initialState = {
  name:'fromDataReducer',
  number: 545
}

export default function dataReducer (state = initialState, action) {
  switch (action.type) {
    case "SET_NAME":
      return {
        ...state,
        name: action.payload
      }
    case "resetName":
      return {
        ...state,
        name: 'ResetFromDataReducer'
      }
    default:
      return state
  }
}

如果我没有连接mapDispatchToProps,那该应用就可以了。但当我connectmapStateToProps时,应用程序将呈现为空白。绝对没有。几秒钟后我收到以下警告:

enter image description here enter image description here

我在index.android.js中的商店是:

const store = createStore( rootReducer );

rootReducer是在我合并Redredrs的地方导入的。我认为store是一个问题,因为它没有mapDispatchToProps工作。

我做错了什么?请帮忙。

1 个答案:

答案 0 :(得分:1)

通过将参数传递给 setName 函数,您可以立即触发它。

尝试使用箭头函数来传递参数:

<Button
    onPress={ () => this.props.setName('newName') }
    title="Click to change Name"
    color="blue"
/>