【发布时间】: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