gpt4 book ai didi

javascript - redux 状态不会改变

转载 作者:行者123 更新时间:2023-11-28 14:29:36 24 4
gpt4 key购买 nike

我已经设置了 redux 存储,但是当我尝试使用 mapStateToProps 和 mapDispatchToProps 更改状态时,我始终得到默认状态。因此,在 account.js 中,我想获取所选语言,然后将其添加到 redux 存储中。我尝试在其他组件中调用它,但最终总是得到reducers/Language.js defaultState。我做错了什么?

Account.js

class Account extends React.Component {
static navigationOptions = ({ navigation }) => {};

constructor(props) {
super(props);

this.state = {
language: {
sq: true,
en: false,
selected: '',
},
};
}

changeLanguage = (selected) => {
if (this.state.sq) {
this.setState({ selected: 'sq' });
} else {
this.setState({ selected: 'en' });
}
};


render() {
const navigation = this.props.navigation;
return (
<ScrollView>
<View>
<ThemeProvider>
<TableView header={I18n.t('account.lang_label')}>
<CheckboxRow
selected={this.state.language.sq}
onPress={() => {
this.setState(state => ({
language: {
sq: !state.language.sq,
en: !state.language.en,
},
}));
this.changeLanguage();
}}
title={I18n.t('account.albanian')}
/>
<CheckboxRow
selected={this.state.language.en}
onPress={() =>
this.setState(state => ({
language: {
en: !state.language.en,
sq: !state.language.sq,
},
}))
}
title={I18n.t('account.english')}
/>
</TableView>
</ThemeProvider>
</View>
</ScrollView>
);
}
}

const mapDispatchToProps = dispatch => {
return {
changeLanguage: (selected) => { dispatch(changeLanguageEn(selected))},
};
};

const mapStateToProps = state => {
return {
language: state.language.selected,

};
};

export default withNavigation(connect(
mapStateToProps,
mapDispatchToProps
)(Account));

actions/Language.js

import {CHANGE_LANGUAGE_EN, CHANGE_LANGUAGE_AL} from "./types";

export const changeLanguageEn = (language) => {
return {
type: CHANGE_LANGUAGE_EN,
lang: language,
}
};

export const changeLanguageAl = (language) => {
return {
type: CHANGE_LANGUAGE_AL,
lang: language,
}
};

reducer /Language.js

const defaultState = {
lang: '',
};

export default function reducer(state = defaultState, action) {
switch (action.type) {
case 'CHANGE_LANGUAGE_EN':
return {...state, lang: 'en'};
case 'CHANGE_LANGUAGE_AL':
return Object.assign({}, state, {
lang: 'sq',
});
default:
return state;
}
}

最佳答案

在您的 mapStateToProps 函数中直接尝试使用 state.lang

const mapStateToProps = state => {
return {
language: state.lang,
};
};

希望这会起作用。

关于javascript - redux 状态不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51998948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com