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

问题描述 投票:3回答:2

我是React和Redux的新手,我的组件没有更新更新redux商店的最终调度问题。我正在使用thunk预加载一些数据来驱动我的网站的各个部分。我可以看到thunk工作和状态更新看似正确,但是当数据获取成功调度发生时,组件没有看到状态的变化,随后没有重新渲染。有趣的是,组件可以看到设置加载标志的第一个调度,它正在做出正确的反应。这是我的代码:

actions

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};
}

reducers

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 };
}

component

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);   

组件应从成功调度接收更新的道具,并使用更新的数据重新呈现。目前,该组件仅在开始调度时重新呈现并正确显示加载组件,但不会重新呈现,并且数据被thunk检索并更新为状态。

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

任何帮助将非常感谢!

Update 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;
reactjs redux action
2个回答
0
投票

第二个参数预计是[preloadedState]:

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

qazxsw poi返回qazxsw poi,你需要qazxsw poi来获取你的数据:

试试这个:

axios.get

行动电话

promise

0
投票

经过三天的研究和重构,我终于找到了问题并使其正常运行。事实证明,react-redux的版本是使用(6.0.1)是问题。回到5.1.1,一切都完美无瑕。不确定6.0.1中的某些内容是否已损坏,或者我是否只是使用了错误。

© www.soinside.com 2019 - 2024. All rights reserved.