2017-08-25 87 views
0

如何將action從我的組件傳遞到reducer無法連接mapDispatchToProps

我的代碼:

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商店:在那裏我已經combinedReducers

const store = createStore(rootReducer); 

rootReducer是進口的。我不認爲store是一個問題,因爲它的工作沒有mapDispatchToProps

我在做什麼錯?請幫忙。

回答

1

通過將參數傳遞給您的setName函數,您將立即觸發它。

嘗試使用,以箭頭函數傳遞參數:

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

這工作!我犯了一個多麼愚蠢的錯誤。因此,如果沒有胖箭頭,函數會嘗試加載,即使沒有點擊?但爲什麼屏幕是空白的? – Somename

+1

是的,應用圓括號會導致函數執行如此封裝在函數中,意味着只有在調用包裝函數時它纔會運行。這很有幫助。 –

+1

激發該動作會導致商店進行更新,從而導致組件重新呈現。如果行動立即被解僱,那麼這可能會導致此過程無限期地循環。 –