Reactjs 无法连接mapDispatchToProps
如何将Reactjs 无法连接mapDispatchToProps,reactjs,react-native,redux,react-redux,Reactjs,React Native,Redux,React Redux,如何将操作从组件传递到减速器 我的代码: import React, { Component } from 'react'; import { Text, View, Button} from 'react-native'; import { connect } from 'react-redux'; class MyApp extends Component { render(){ return( <View> <Te
操作
从组件传递到减速器
我的代码:
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 )
如果我不连接mapDispatchToProps
,应用程序工作正常。但是当我用MapStateTrops
连接它时,应用程序被呈现为空白。绝对没有。几秒钟后我收到以下警报:
我在index.android.js中的存储是:
const store = createStore( rootReducer );
rootReducer
是在我组合了reducer的地方导入的。我不知道;我不认为store
是个问题,因为它在没有mapDispatchToProps
的情况下工作
我做错了什么?请提供帮助。通过将参数传递给您的setName函数,您将立即启动它 尝试使用箭头函数传递参数:
<Button
onPress={ () => this.props.setName('newName') }
title="Click to change Name"
color="blue"
/>
this.props.setName('newName')}
title=“单击以更改名称”
color=“蓝色”
/>
真管用!我犯了一个多么愚蠢的错误。因此,如果没有胖箭头,函数甚至不单击也会尝试加载?但是为什么屏幕是空白的呢?是的,应用括号会导致函数执行,所以将它包装在函数中意味着只有在调用包装函数时它才会运行。很高兴这有帮助。触发操作会导致存储更新,从而导致组件重新呈现。如果立即触发该操作,则可能导致该进程无限期地循环。
<Button
onPress={ () => this.props.setName('newName') }
title="Click to change Name"
color="blue"
/>