React组件不会在最终调度和Redux状态更新时更新

时间:2019-04-04 13:58:59

标签: reactjs redux action

我对React和Redux还是很陌生,但是我的组件没有在更新Redux存储的最终分发中没有更新的问题。我正在使用thunk来预加载一些数据以驱动网站的各个部分。我可以看到thunk正常工作并且状态更新似乎正确,但是当数据获取成功调度发生时,组件没有看到状态变化,因此也没有重新呈现。有趣的是,设置加载标志的第一个调度正被组件看到,并且它的反应正确。这是我的代码:

动作

import { programsConstants } from '../constants';
import axios from 'axios'

export const programsActions = {
    begin,
    success,
    error,
};

export const loadPrograms = () => dispatch => {
    dispatch(programsActions.begin());

    axios
        .get('/programs/data')
        .then((res) => {
            dispatch(programsActions.success(res.data.results));
        })
        .catch((err) => {
            dispatch(programsActions.error(err.message));
        });
};

function begin() {
    return {type:programsConstants.BEGIN};
}
function success(data) {
    return {type:programsConstants.SUCCESS, payload: data};
}
function error(message) {
    return {type:programsConstants.ERROR, payload:message};
}

减速器

import {programsConstants} from '../constants';
import React from "react";

const initialState = {
    data: [],
    loading: false,
    error: null
};

export function programs(state = initialState, action) {
    switch (action.type) {
        case programsConstants.BEGIN:
            return fetchPrograms(state);
        case programsConstants.SUCCESS:
            return populatePrograms(state, action);
        case programsConstants.ERROR:
            return fetchError(state, action);
        case programsConstants.EXPANDED:
            return programsExpanded(state, action);
        default:
            return state
    }
}

function fetchPrograms(state = {}) {
    return { ...state, data: [], loading: true, error: null };
}

function populatePrograms(state = {}, action) {
   return { ...state, data: action.payload, loading: false, error: null };
}

function fetchError(state = {}, action) {
    return { ...state, data: [], loading: false, error: action.payload };
}

组件

import React from "react";
import { connect } from 'react-redux';
import { Route, Switch, Redirect } from "react-router-dom";
import { Header, Footer, Sidebar } from "../../components";
import dashboardRoutes from "../../routes/dashboard.jsx";
import Loading from "../../components/Loading/Loading";
import {loadPrograms} from "../../actions/programs.actions";

class Dashboard extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.props.dispatch(loadPrograms());
  }

  render() {
    const { error, loading } = this.props;

    if (loading) {
      return <div><Loading loading={true} /></div>
    }
    if (error) {
      return <div style={{ color: 'red' }}>ERROR: {error}</div>
    }

    return (
      <div className="wrapper">
        <Sidebar {...this.props} routes={dashboardRoutes} />
        <div className="main-panel" ref="mainPanel">
          <Header {...this.props} />
          <Switch>
            {dashboardRoutes.map((prop, key) => {
              let Component = prop.component;
              return (
                  <Route path={prop.path} component={props => <Component {...props} />} key={key} />
              );
            })}
          </Switch>
          <Footer fluid />
        </div>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  loading: state.programs.loading,
  error: state.programs.error
});

export default connect(mapStateToProps)(Dashboard);   

组件应从成功调度中接收更新的道具,并使用更新的数据重新呈现。当前,该组件仅在begin调度时重新呈现,并正确显示正在加载的组件,但不会随着thunk检索数据并将其更新为状态而重新呈现。

我已经研究了这几天,并且普遍认为组件无法获得状态刷新的原因是无意的状态突变,而不是返回新状态。我不认为我正在改变国家,但也许我是。

任何帮助将不胜感激!

更新1

根据要求,这里是创建商店和合并化简器的代码

商店:

const loggerMiddleware = createLogger();
const composeEnhancers =
    typeof window === 'object' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
        window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
        }) : compose;

const enhancer = composeEnhancers(
    applyMiddleware(
        thunk,
        loggerMiddleware)
);

export const store = createStore(rootReducer, enhancer);

减速器组合:

import { combineReducers } from 'redux';
import { alert } from './alert.reducer';
import { programs } from './programs.reducer';
import { sidenav } from './sidenav.reducer';

const rootReducer = combineReducers({
  programs,
  sidenav,
  alert
});

export default rootReducer;

2 个答案:

答案 0 :(得分:0)

第二个参数应为 [preloadedState]

export const store = createStore(rootReducer, {} , enhancer);

axios.get返回promise所需的await来获取数据:

尝试一下:

   export const loadPrograms = () => async (dispatch) => {
      dispatch(programsActions.begin());

      try {
        const res = await axios.get('/programs/data');
        const data = await res.data;
        console.log('data recieved', data)
        dispatch(programsActions.success(data.results));
      } catch (error) {
        dispatch(programsActions.error(error));
      }
    };


const mapStateToProps = state => ({
  loading: state.programs.loading,
  error: state.programs.error,
  data: state.programs.data,
});

行动电话

import React from 'react';
import { connect } from 'react-redux';
import { loadPrograms } from '../../actions/programs.actions';

class Dashboard extends React.Component {
  componentDidMount() {
    // Try to call you action this way:
    this.props.loadProgramsAction(); // <== Look at this
  }
}

const mapStateToProps = state => ({
  loading: state.programs.loading,
  error: state.programs.error,
});

export default connect(
  mapStateToProps,
  {
    loadProgramsAction: loadPrograms,
  },
)(Dashboard);

答案 1 :(得分:0)

经过三天的研究和重构,我终于找到了问题,并使它起作用。原来,问题是使用react-redux的版本正在使用(6.0.1)。回滚到5.1.1,一切正常。不知道6.0.1中是否有问题或我是否使用错误。