反应本地Redux。状态正在更新,但组件尚未重新呈现

时间:2019-03-12 17:00:31

标签: javascript reactjs react-native redux react-redux

我正在使用Redux开发应用程序。

在以下代码段中,我切换了appEnabled状态:

excludes

以下是映射功能:

...
render() {
    const { appEnabled } = this.props;
    const { updatePreferences } = this.props;

    return (
        <View style={styles.preferences}>
                <Text>App enabled: {appEnabled + ''}</Text>
                <Button onPress={() => updatePreferences({ appEnabled: !appEnabled })}>Toggle AppEnabled</Button>
        </View>)
}

状态更新正常。但是,组件的重新呈现不会发生。

我知道常见原因可能是偶然的状态突变。我确保reducer函数每次都返回新对象:

function mapStateToProps({ preferences }) {
    return {
        appEnabled: preferences.appEnabled,
    };
}

function mapDispatchProps(dispatch) {
    return {
        getPreferences,
        updatePreferences: (preferences) => dispatch(updatePreferencesAction(preferences))
    };
}

export default connect(mapStateToProps, mapDispatchProps)(PreferenceScreen);

在我的情况下,不重新提交组件的原因可能是什么?

2 个答案:

答案 0 :(得分:0)

如果不看完整的代码就很难分辨,如果添加jsfiddle则更容易获得帮助。

无论如何,您的组件看起来不错,并且应该在道具更改时更新。在Reducer中更新状态的方式似乎唯一有些奇怪。我不能仅通过查看减速器就知道状态的形状,例如,为什么要用state = {...defaultState}而不是state = defaultState

return {...state, ...action.preferences }也令人怀疑。在大多数情况下,状态是这样更新的:return { ...state, preferences: action.preferences },因为它可以使减速器变得更加清晰。

我建议您进行这些更改,然后使用redux devtools进行彻底调试。

答案 1 :(得分:0)

更改

function mapStateToProps({ preferences }) {
return {
    appEnabled: preferences.appEnabled,
};

}

收件人

function mapStateToProps({ appEnabled }) {
return {
    appEnabled: appEnabled,
};
相关问题