是Redux的新手
我只是想在多个屏幕上显示价值。我需要在OnPress之后更新并显示商店价值。
我的商店
import { createStore } from "redux";
// const rootReducer = () => {
// }
import rootReducer from "../reducers/index.js";
export default store = createStore(rootReducer);
我的余额减少器
const BalanceReducer = (state = '0', action) => {
switch (action.type) {
case 'UPDATE_BAL':
return state
default:
return state
}
}
export default BalanceReducer;
我的组件
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, Button } from 'react-native';
import { connect } from "react-redux";
class StartPage extends Component {
_UpdateBal = () => {
const text = 30;
this.props.dispatch({ type: 'UPDATE_BAL', text });
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Current Balance : {this.props.balance} </Text>
<Button title={'Update Balance'} onPress={this._UpdateBal} />
<Button title={'Login ->'} onPress={() => this.props.navigation.navigate('login')} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
export default connect()(StartPage);
让我知道我在哪里做错了。我无法在此获得价值。props.balance和调度操作似乎也没有更新。
答案 0 :(得分:0)
我在rootReducer内看不到,所以我假设您正在正确注册Balance Reducer。但是在余额减少器中,您的UPDATE_BAL
操作实际上没有做任何事情-它只是返回状态'0'
。请注意,这是值为“ 0”的字符串,而不是值为0的数字。您想在组件中将余额设置为数字。要解决此问题,您可以执行以下操作:
const BalanceReducer = (state = 0, action) => {
switch (action.type) {
case 'UPDATE_BAL':
return state + action.text //add the action's value (which you send over from your component) to the stored value
default:
return state
}
}
export default BalanceReducer;
除此之外,您还缺少一个mapStateToProps
,它实际上将您的应用程序状态映射到您的StartPage
组件的道具:
const mapStateToProps = (state) => {
return {
balance: state.BalanceReducer //now you can acccess the balance through this.props.balance
}
}
export default connect(mapStateToProps)(StartPage);