我有一个使用 React + Redux + Thunk 的项目,我对该堆栈相当陌生。我有一个场景,我从操作/ reducer 中的 API 调用中获取数组,但它不会在连接到 Store 的组件/容器中重新渲染。当我启动应用程序时,该组件确实会第一次渲染,但此时当登录到控制台时,该数组是未定义
。
我试图显示数组的长度,所以这总是导致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));
我怀疑我要么改变了 reducer 中的状态,要么滥用了 Thunk。
最佳答案
代码中的问题是 connections.data.forEach((value) => {..})
会发出一堆 fetch,然后立即返回而不等待结果要填充的数组。 'FETCH_CONNECTIONS'
操作使用空数组进行调度,所有连接的组件都将使用空结果重新渲染。
但棘手的是,一旦提取完成,您放入存储中的数组对象就会被推送到,因此当您检查存储时,它看起来会正确填充。
不使用任何突变将防止商店意外填充,但无法解决在结果进入之前触发调度的事实。为此,您可以创建操作来添加单个结果并将其调度到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,则可以使其更漂亮一些。
关于javascript - React Redux 状态数组更改不会重新渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49776410/