首页 > 解决方案 > React Native,Redux 在 combineReducer 之后不会在状态更改时更新组件

问题描述

堆栈溢出神,

我是 Redux 的新手,我正在从数据库中提取数据并使用它使用 Redux Thunk 为 Redux 创建一个初始状态对象。

我的减速器文件结构目前看起来像:

当我拥有在 index.js 中处理这些交互的 reducer 时,我的组件会完美地重新渲染:

import {GET_INITIAL_DATA_FULFILLED, GET_INITIAL_DATA_PENDING, GET_INITIAL_DATA_REJECTED} from '../constants/action-types'

const initialState = {
  chats : [],
  messages: [],
  user: {},
  loading:true,
  errorMessage:''
}

const reducer = (state = initialState, action) => {
  switch(action.type){
    case GET_INITIAL_DATA_PENDING:
      // console.log('loading')
      return {
        ...state,
        loading:action.payload
      };
    case GET_INITIAL_DATA_FULFILLED:
      // console.log('Data recieved')
      return {
        ...state,
        user: action.payload.user,
        messages:action.payload.messages,
        chats: action.payload.chats,
        loading:action.loading
      };
    case GET_INITIAL_DATA_REJECTED:
      // console.log('Error getting data')
      return {
        ...state,
        errorMessage: action.payload,
        loading: action.loading
      };
    default:

      return state;
  }
}

export default reducer

但是,当我想将它与根 reducer 分离并切换到使用 combineReducer 时,组件不再重新渲染。这就是实现:

index.js

import { combineReducers } from 'redux';
import initialData from './initialData'

export default combineReducers({
  initialData
})

初始数据.js

import {GET_INITIAL_DATA_FULFILLED, GET_INITIAL_DATA_PENDING, GET_INITIAL_DATA_REJECTED} from '../constants/action-types'

const initialState = {
  chats : [],
  messages: [],
  user: {},
  loading:true,
  errorMessage:''
}

const initialData = (state = initialState, action) => {
  switch(action.type){
    case GET_INITIAL_DATA_PENDING:
      console.log('loading')
      return {
        ...state,
        loading:action.payload
      };
    case GET_INITIAL_DATA_FULFILLED:
      console.log('Data recieved')
      return {
        ...state,
        user: action.payload.user,
        messages:action.payload.messages,
        chats: action.payload.chats,
        loading:action.loading
      };
    case GET_INITIAL_DATA_REJECTED:
      console.log('Error getting data')
      return {
        ...state,
        errorMessage: action.payload,
        loading: action.loading
      };
    default:
      return {...state};
  }
}

export default initialData

如果有人对为什么我的组件没有重新渲染有任何想法,尽管收到了数据并且状态正在更新,我很想听听他们的意见。

标签: javascriptreactjsreact-nativereduxreact-redux

解决方案


弄清楚了。combineReducer 在状态对象上创建一个新属性。所以组件只是呈现一个未定义的状态,因为我没有检查那个新属性。


推荐阅读