React Redux状态数组更改不会重新呈现组件

时间:2018-04-11 13:27:32

标签: javascript reactjs redux redux-thunk

我有一个使用React + Redux + Thunk的项目,我对堆栈很新。我有一个场景,我从我的action / reducer中的API调用中获取一个数组,但它不会在连接到Store的组件/容器中重新呈现。当我启动应用程序时,组件会第一次呈现,但此时,当记录到控制台时,数组为undefined

我正在尝试显示数组的长度,因此总是会产生0。使用ReduxDevTools,我发现network_identities的状态确实正确填充并且更长零...我哪里出错了?

以下是我的示例操作

///////////// Sample action ///////////// 
import axios from 'axios';

const url = 'sample@url.com';
const authorization = 'sample_auth';

export function fetchConnections() {

    const params = {
            headers: {
            authorization,
        },
    };

    return (dispatch) => {
        // call returns an array of items
        axios.get(`${url}/connection`, params)
        .then((connections) => {

            let shake_profiles = [];
            let connected_profiles = [];
            let entity_res;

            // map through items to fetch the items data, and split into seperate arrays depending on 'status'
            connections.data.forEach((value) => {
                switch (value.status) {
                case 'APPROVED': case 'UNAPPROVED':
                    {
                    axios.get(`${url}/entity/${value.entity_id_other}`, params)
                    .then((entity_data) => {
                        entity_res = entity_data.data;
                        // add status
                        entity_res.status = value.status;
                        // append to connected_profiles
                        connected_profiles.push(entity_res);
                    });
                    break;
                    }
                case 'CONNECTED':
                    {
                    axios.get(`${url}/entity/${value.entity_id_other}`, params)
                    .then((entity_data) => {
                        entity_res = entity_data.data;
                        entity_res.status = value.status;
                        shake_profiles.push(entity_res);
                    })
                    .catch(err => console.log('err fetching entity info: ', err));
                    break;
                    }
                // if neither case do nothing
                default: break;
                }
            });

            dispatch({
                type: 'FETCH_CONNECTIONS',
                payload: { shake_profiles, connected_profiles },
            });
        });
    };
}

Sample Reducer

///////////// Sample reducer ///////////// 
const initialState = {
    fetched: false,
    error: null,
    connections: [],
    sortType: 'first_name',
    filterType: 'ALL',
    shake_identities: [],
    network_identities: [],
};

const connectionsReducer = (state = initialState, action) => {
    switch (action.type) {
    case 'FETCH_CONNECTIONS':
        console.log('[connections REDUCER] shake_profiles: ', action.payload.shake_profiles);
        console.log('[connections REDUCER] connected_profiles: ', action.payload.connected_profiles);
        return { ...state,
        fetched: true,
        shake_identities: action.payload.shake_profiles,
        network_identities: action.payload.connected_profiles,
        };
    default:
        return state;
    }
};

export default connectionsReducer;

样本商店

///////////// Sample Store /////////////
import { applyMiddleware, createStore, compose } from 'redux';
import thunk from 'redux-thunk';
import promise from 'redux-promise-middleware';
import reducers from './reducers';

const middleware = applyMiddleware(promise(), thunk);
// Redux Dev Tools
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducers, composeEnhancers(middleware));

export default store;

示例组件 - 查看API是否完成获取数组,然后显示数组的长度

///////////// Sample Component /////////////
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import CSSModules from 'react-css-modules';
import * as ConnectionActions from 'actions/connections';

import styles from './styles.scss';

function mapStateToProps(state) {
return {
    network_identities: state.connections.network_identities,
    loadedConnections: state.connections.fetched,
};
}

function mapDispatchToProps(dispatch) {
return {
    actions: bindActionCreators(Object.assign({}, ConnectionActions), dispatch),
};
}

class Counter extends Component {
componentWillMount() {
    const { network_identities, actions } = this.props;
    if (!network_identities.length) {
    console.log('||| fetching Connections');
    actions.fetchConnections();
    }
}

render() {
    let { network_identities, loadedConnections} = this.props;

    console.log('[Counter] network_identities[0]: ', network_identities[0]);
    console.log('[Counter] network_identities: ', network_identities);
    console.log('[Counter] loadingConnections: ', loadingConnections);

    return (
    <div>
        <Link to="/network">
        <div>
            <span>Connections</span>
            { !loadedConnections ? (
            <span><i className="fa fa-refresh fa-spin" /></span>
            ) : (
            <span>{network_identities.length}</span>
            ) }
        </div>
        </Link>
    </div>
    );
}
}

export default connect(mapStateToProps, mapDispatchToProps)(CSSModules(Counter, styles));

我怀疑我要么在减速器中改变状态,要么我在误用Thunk。

2 个答案:

答案 0 :(得分:1)

这里的问题是你在componentWillMount中进行异步操作。调用此生命周期方法时,它不会阻止调用render方法。也就是说,它不会等到其操作得到响应。因此,请将此异步操作移至componentDidMount。

答案 1 :(得分:1)

代码中的问题是connections.data.forEach((value) => {..})将发送一堆提取,然后立即返回而不等待填充结果数组。使用空数组调度'FETCH_CONNECTIONS'操作,并且所有连接的组件将使用空结果重新呈现。

令人困惑的是,一旦提取完成,你放入商店的数组对象就会被推送到,所以当你检查商店时,它似乎会被正确填充。

不使用任何突变会阻止商店的意外填充,但不能解决在结果进入之前发送调度的事实。为此,您可以创建操作以添加单个结果并将其分发到axios.get().then部分,或者您可以创建承诺列表,并等待所有承诺通过Promise.all()解决。

以下是后一种解决方案的样子。

axios.get(`${url}/connection`, params)
.then((connections) => {

  const connectionPromises = connections.data.map((value) => {
    switch (value.status) {
      case 'APPROVED': case 'UNAPPROVED':
        return axios.get(`${url}/entity/${value.entity_id_other}`, params)
        .then((entity_data) => {
          return {connected_profile: {...entity_data.data, status: value.status}};
        });
      case 'CONNECTED':
        return axios.get(`${url}/entity/${value.entity_id_other}`, params)
        .then((entity_data) => {
            return {shake_profile: {...entity_data.data, status: value.status}};
        })
      // if neither case do nothing
      default:
        return {};
    }
  });

  Promise.all(connectionPromises)
  .then((connections) => {
    const connected_profiles =
      connections.filter((c) => c.connected_profile).map((r) => r.connected_profile);
    const shake_profiles =
      connections.filter((c) => c.shake_profile).map((r) => r.shake_profile);

    dispatch({
      type: 'FETCH_CONNECTIONS',
      payload: { shake_profiles, connected_profiles },
    });
  }).catch(err => console.log('err fetching entity info: ', err));

});

你可能想要使用一些更合适的名字,如果你使用lodash,你可以让它更漂亮。