我不确定这是否是正确的做事方式,或者甚至是否可能,因此我的问题在这里。
我在我的项目中使用react-redux,redux-thunk,json-server(用于虚拟数据)和typescript。通过1 api调用,我使用我的应用程序的所有数据更新'data'减速器。此数据通过combineReducers:Redux tree与其他reducer一起使用
我想做的是将data.labels作为prop映射到我的组件中。一旦整个api调用完成,并且data.labels因此被填充,我想将这些数据显示给我的前端。但我注意到,当我的数据api调用完成时,根本不会触发componentWillReceiveProps。如果我将整个'data'道具附加到我的组件而不是'data.labels',它会更新。
减速器:
case Actions.RECEIVE:
return {
...state,
labels: action.payload.labels,
defaultLinks: action.payload.defaultLinks,
customLinks: action.payload.customLinks
};
零件:
function mapStateToProps(state: any) {
return {
labels: state.data.labels, // This will not trigger componentWillReceiveProps
function mapStateToProps(state: any) {
return {
data: state.data, // This will trigger componentWillReceiveProps
有关如何在不将整个数据对象作为道具注入的情况下使其工作的任何提示?
编辑
在使用完整的“数据”的情况下,在获取数据之前,在componentWillReceiveProps中记录data.labels时,我得到一个空的标签数组。成功获取数据后,我的日志显示x个标签数组。
下面是我使用的接口:数据接口(redux存储区内的结构,'data'作为父级):
interface Data {
labels: Label[];
defaultLinks: DefaultLink[];
customLinks: CustomLink[];
request: boolean;
failure: boolean;
}
我的组件中使用的道具接口:
interface Props {
labels: Label[];
...; // Other stuff
}
您可能正在寻找选择器模式:gist.github.com/abhiaiyer91/aaf6e325cf7fc5fd5ebc70192a1fa170经常与重新选择结合使用:github.com/reactjs/reselect#reselect
主要优点是您可以将状态的形状与道具的形状分离。