【问题标题】:React Redux state array changes are not re-rendering a componentReact Redux 状态数组更改不会重新渲染组件
【发布时间】:2018-04-11 13:27:32
【问题描述】:

我有一个使用 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 ///////////// 
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。

【问题讨论】:

  • 快速提问,你使用的是什么版本的 react?从 React 16 开始有一些变化可能会改变这个问题的答案。在 16 之前,您可以使用 componentWillReceiveProps() 生命周期函数,事实上,即使在 React 16 之后,我认为您仍然会使用它来同步更新状态。将一些内容传递给 componentWillReceiveProps(nextProps) 和 console.log nextProps,您应该会看到您的更改,然后您可以根据需要使用这些更改来更新组件。
  • 与您的问题无关,我建议将 api 客户端逻辑与操作分开。诸如设置自定义标头和授权之类的事情不应在动作创建者模块中处理。
  • @Ron React 是 15.6.2 版。将尝试该策略,谢谢!
  • connections.data.forEach 是粗略的,因为它不会等到提取完成。获取之后会改变状态,但不会触发重新渲染,因为调度已经触发。将connections 映射到promise 并使用.all() 等待结果可能会更好。
  • @AdB 我仔细检查过,即使在 16 中也应该没问题。16.3 是发生变化的地方,现在这被认为是遗留的生命周期方法。这篇文章比我能解释得更好。 medium.com/@baphemot/whats-new-in-react-16-3-d2c9b7b6193b 我还在下面添加了一个更深入的示例作为答案。

标签: javascript reactjs redux redux-thunk


【解决方案1】:

代码中的问题是connections.data.forEach((value) =&gt; {..})会发出一堆fetch,然后立即返回,而不用等待结果数组被填充。 'FETCH_CONNECTIONS' action 使用空数组调度,所有连接的组件将使用空结果重新渲染。

但棘手的是,一旦提取完成,您放入存储中的数组对象将被推送到,因此当您检查存储时,它看起来会正确填充。

不使用任何突变将防止商店的意外填充,但不会解决在结果进入之前触发调度的事实。为此,您可以创建操作以添加单个结果并将其调度axios.get().then 部分,或者您可以创建一个 Promise 列表并等待它们全部使用 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,您可以让它更漂亮一些。

【讨论】:

  • 就是这样!非常感谢!你能解释一下双重回报吗?这部分让我很困惑:return axios.get('content', params) .then((entity_data) =&gt; { return {connected_profile: {...entity_data.data, status: value.status}}; });
  • 外层返回是将promise返回给map回调,所以它最终在数组中。内部返回是返回 promise 将解析为的值。如果您愿意,可以通过将(arg) =&gt; {return {...}} 重写为(arg) =&gt; ({...}) 来摆脱内部返回。
【解决方案2】:

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

【讨论】:

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