【问题标题】:React Native, Redux not updating components on state change after combineReducerReact Native,Redux 在 combineReducer 之后不会在状态更改时更新组件
【发布时间】:2020-09-22 20:59:10
【问题描述】:

堆栈溢出之神,

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

我的 reducer 文件结构目前如下所示:

  • 减速机
    • index.js
    • initialData.js

当我拥有在 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
})

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

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-12
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多