首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法连接mapDispatchToProps

无法连接mapDispatchToProps
EN

Stack Overflow用户
提问于 2017-08-25 18:21:37
回答 1查看 187关注 0票数 0

如何从组件将action传递给reducer

我的代码:

代码语言:javascript
复制
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

代码语言:javascript
复制
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一起使用它时,应用程序被呈现为空白。什么事也没有。几秒钟后我会收到以下警告:

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

代码语言:javascript
复制
const store = createStore( rootReducer );

rootReducer是在我有combinedReducers的地方导入的。我不认为store是一个问题,因为没有mapDispatchToProps,它是有效的。

我做错了什么?请帮帮忙。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-25 18:27:12

通过将一个参数传递给您的setName函数,您将立即触发它。

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

代码语言:javascript
复制
<Button
    onPress={ () => this.props.setName('newName') }
    title="Click to change Name"
    color="blue"
/>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45887418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档