如何从组件将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,这个应用程序就能正常工作。但是当我用connect与mapStateToProps一起使用它时,应用程序被呈现为空白。什么事也没有。几秒钟后我会收到以下警告:


我在index.android.js的商店是:
const store = createStore( rootReducer );rootReducer是在我有combinedReducers的地方导入的。我不认为store是一个问题,因为没有mapDispatchToProps,它是有效的。
我做错了什么?请帮帮忙。
发布于 2017-08-25 18:27:12
通过将一个参数传递给您的setName函数,您将立即触发它。
尝试使用箭头函数来传递参数:
<Button
onPress={ () => this.props.setName('newName') }
title="Click to change Name"
color="blue"
/>https://stackoverflow.com/questions/45887418
复制相似问题