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
,應用程序工作正常。但當我connect
與mapStateToProps
,該應用程序呈現爲空白。絕對沒有。我也得到了以下警報,幾秒鐘後:
我在index.android.js商店:在那裏我已經combinedReducers
const store = createStore(rootReducer);
rootReducer
是進口的。我不認爲store
是一個問題,因爲它的工作沒有mapDispatchToProps
。
我在做什麼錯?請幫忙。
這工作!我犯了一個多麼愚蠢的錯誤。因此,如果沒有胖箭頭,函數會嘗試加載,即使沒有點擊?但爲什麼屏幕是空白的? – Somename
是的,應用圓括號會導致函數執行如此封裝在函數中,意味着只有在調用包裝函數時它纔會運行。這很有幫助。 –
激發該動作會導致商店進行更新,從而導致組件重新呈現。如果行動立即被解僱,那麼這可能會導致此過程無限期地循環。 –