【发布时间】:2021-06-03 03:19:31
【问题描述】:
我使用 Redux 为我的导航栏设置了三个计数器。我可以访问初始状态的值。但我无法更改这些值。我的 Reducer 看起来像这样:
const SET_FREUNDE = 'SET_FREUNDE';
const SET_CHATS = 'SET_CHATS';
const SET_VOTES = 'SET_VOTES';
export function setFreunde(value) {
return {
type: SET_FREUNDE,
value,
}
}
export function setChats(value) {
return {
type: SET_CHATS,
value,
}
}
export function setVotes(value) {
return {
type: SET_VOTES,
value,
}
}
const defaults =
{
countervotes: 2,
counterchats: 1,
counterfreunde: 1
};
function counter(state=defaults, action) {
switch (action.type) {
case SET_FREUNDE:
return {...state,counterfreunde: action.value}
case SET_CHATS:
return {...state,counterchats: action.value}
case SET_VOTES:
return {...state,countervotes: action.value}
default:{
return state;
}
}
}
export default counter;
现在我想在另一个屏幕上设置计数器:
import * as React from "react";
import { Image, StyleSheet,... } from "react-native";
...
import {connect} from 'react-redux';
import { setChats, setFreunde, setVotes } from '../redux/counter';
class ... extends React.Component<{}, State> {
constructor(props) {
super(props);
}
...
render(){
return(
<SafeAreaView style={styles.container}>
<Button onPress={() => setFreunde(2)}/>
...
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
...
});
const mapDispatchToProps = (dispatch, ownProps) => ({
setFreunde: () => {
const { value } = ownProps
dispatch(setFreunde(value))
},
setChats: () => {
const { value } = ownProps
dispatch(setChats(value))
},
setVotes: () => {
const { value } = ownProps
dispatch(setVotes(value))
}
})
export default connect( null, mapDispatchToProps )(NavStack)
如果我记录 setFreunde(2),控制台会显示以下内容:
对象{“类型”:“SET_FREUNDE”,“值”:2,}
但是,我在 App.tsx 中检索到的值没有改变,如下所示:
const counterfreunde = useSelector((state)=>state.counterfreunde);
我的错误是什么?
【问题讨论】:
-
您只有
counter状态吗?counterfreunde选择器是返回初始值还是未定义? -
选择器返回初始状态。我有三个计数器状态
标签: react-native redux react-redux expo