组件的 prop 不会在带有 Redux 的 React Native 中更新

小丑

我的应用程序和 Redux 需要一些帮助!(目前,我讨厌它啊哈)

所以,我有一个获取一些数据的通知页面组件,我需要将数据长度放入我的 redux 存储中,以便在我的标签栏中的图标上放置徽章!

我的主减速器:

import { combineReducers } from "redux";
import NotificationReducer from "./NotificationReducer";

export default function getRootReducer(navReducer) {
    return combineReducers({
        nav: navReducer,
        notificationReducer: NotificationReducer
    });
}

我的通知减速器

const initialState = {
    NotificationCount: 0
};

export default function notifications(state = initialState, action = {}) {
    switch (action.type) {
        case 'SET_COUNT' :
            console.log('REDUCER NOTIFICATION SET_COUNT',state)
            return {
                ...state,
                NotificationCount: action.payload
            };

        default:
            return state;
    }
};

我的行动:

export function setNotificationCount(count) {
    return function (dispatch, getState) {
          console.log('Action - setNotificationCount: '+count)
          dispatch( {
            type: 'SET_COUNT',
            payload: count,
          });
    };
};

我的组件:

import React, { Component } from 'react';
import { View, Text, StyleSheet, ScrollView, Dimensions, TouchableOpacity, SectionList, Alert } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { Notification } from '@Components';
import { ORANGE } from '@Theme/colors';
import { NotificationService } from '@Services';
import Style from './style';

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as Actions from '@Redux/Actions';

const width = Dimensions.get('window').width
const height = Dimensions.get('window').height

export class NotificationsClass extends Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            NotificationCount: undefined
        };
    }

    async componentWillMount() {
        this.updateNotifications();
    }

    componentWillReceiveProps(nextProps){
        console.log('receive new props',nextProps);
    }

    async updateNotifications() {
        this.props.setNotificationCount(10); <---
        let data = await NotificationService.get();
        if (data && data.data.length > 0) {
            this.setState({ dataSource: data });
            console.log(this.props) <-- NotificationCount is undefined
        }
    }


    render() {
        if (this.state.dataSource.length > 0) {
            return (
                <SectionList
                    stickySectionHeadersEnabled
                    refreshing
                    keyExtractor={(item, index) => item.notificationId}
                    style={Style.container}
                    sections={this.state.dataSource}
                    renderItem={({ item }) => this.renderRow(item)}
                    renderSectionHeader={({ section }) => this.renderSection(section)}
                />
            );
        } else {
            return this.renderEmpty();
        }
    }

    renderRow(data) {
        return (
            <TouchableOpacity activeOpacity={0.8} key={data.notificationId}>
                <Notification data={data} />
            </TouchableOpacity>
        );
    }


}


const Notifications = connect(
    state => ({
        NotificationCount: state.NotificationCount
    }),
    dispatch => bindActionCreators(Actions, dispatch)
)(NotificationsClass);


export { Notifications };

(我删除了一些无用的代码)

顶层 :

const navReducer = (state, action) => {
    const newState = AppNavigator.router.getStateForAction(action, state);
    return newState || state;
};

@connect(state => ({
    nav: state.nav
}))
class AppWithNavigationState extends Component {
    render() {
        return (
            <AppNavigator
                navigation={addNavigationHelpers({
                    dispatch: this.props.dispatch,
                    state: this.props.nav,
                })}
            />
        );
    }
}

const store = getStore(navReducer);

export default function NCAP() {
    return (
        <Provider store={store}>
            <AppWithNavigationState />
        </Provider>
    );
}

React:15.6.1 React-Native:0.46.4 Redux:3.7.2 React-Redux:5.0.5 React-Navigation:1.0.0-beta.11 Node:6.9.1

所以,如果你有想法!会很棒:D!

谢谢 !

马克森

有三个问题。

首先,React 的重新渲染几乎总是异步的。在 中updateNotifications(),您正在调用this.props.setNotificationCount(10),但尝试稍后在该函数中查看/使用道具。即使await在那里,也不能保证this.props.NotificationCount已经更新。

其次,基于你的reducer结构和mapState功能,props.NotificationCount实际上永远不会存在在你的getRootReducer()函数中,你有:

return combineReducers({
    nav: navReducer,
    notificationReducer: NotificationReducer
});

这意味着您的根状态将是state.navand state.notificationReducer但是,在您的mapState函数中,您有:

state => ({
    NotificationCount: state.NotificationCount
}),

state.NotificationCount永远不会存在,因为您在调用combineReducers.

第三,您notificationReducer实际上有一个嵌套值。它回来了{NotificationCount : 0}

所以,你真正想要的值真的是state.notificationReducer.NotificationCount这意味着您的mapState功能实际上应该是:

state => ({
    NotificationCount: state.notificationReducer.NotificationCount
}),

如果您notificationReducer实际上不打算存储任何其他值,我建议对其进行简化,使其仅存储数字,而不是对象内部的数字。我还建议Reducer从您的州切片名称中删除这个词这样,您可以state.notification改为参考

有关更多信息,请参阅Redux 文档Structuring Reducers - UsingcombineReducers部分,其中详细介绍了 using 如何combineReducers定义您的状态形状。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React Native更改let值不会在子组件中作为prop更改

Connected Component的prop在带有Redux的React Native中不会更新

Redux Reducer不会从React组件外部的调度更新React组件中的prop值

React Native 组件不会在计算后立即更新

数组中的React Child组件不会在prop更改时更新

如何优化React + Redux中嵌套组件的prop的小更新?

React Redux:我的React组件没有收到更新的数组作为prop

已解决:React Redux的useSelector不会在expo react-native上更新存储状态

React Native:基于Array.map()的渲染组件不会在状态更改时更新

React - 道具不会在整个组件中更新相同

为什么我的Animated API组件不会在React Native中显示?

React + Redux。Connect不会更新组件的状态

React 组件不会在更新状态时更新

React Native / Redux - 只能更新已安装或正在安装的组件

React Native Stack Navigator 不接受 Screen 作为组件 prop 中的 prop

React JS组件不会在状态更改时更新

React Native不会更新子组件的道具

使用 redux 结构执行任务后,组件未在 react-native 中更新

单击复选框时,带有复选框的React / Redux组件不会更新

React Native组件没有从Redux获取this.props.dispatch

React不会在组件中触发功能

Route 不会在 React 中渲染组件

动作不会在React + Redux中触发reducer

React-redux:后续相同类型的兄弟组件不会随着不同的 Prop 值而改变

React-Redux存储或将prop中的api传递给组件,这是更好的方法

D3组件不会在React中更新

React-redux组件不会在商店状态更改时重新呈现

React Redux-子组件不会在状态更改时重新呈现

React / Redux组件不会在状态更改时重新呈现