2

我不确定这是否是正确的做事方式,或者是否有可能,因此我的问题在这里。

我在我的项目中使用 react-redux、redux-thunk、json-server(用于虚拟数据)和 typescript。通过 1 个 api 调用,我用我的应用程序的所有数据更新了“数据”reducer。这些数据通过 combineReducers 与其他 reducer 一起使用: Redux 树

我想做的是将 data.labels 作为道具映射到我的组件中。一旦整个 api 调用完成并因此填充了 data.labels,我想将这些数据显示给我的前端。然而,我注意到,当我的数据 api 调用完成时,根本不会触发 componentWillReceiveProps。如果我将整个“数据”道具附加到我的组件而不是“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
}
4

1 回答 1

2

您可能正在寻找选择器模式:gist.github.com/abhiaiyer91/aaf6e325cf7fc5fd5ebc70192a1fa170经常与重新选择结合使用:github.com/reactjs/reselect#reselect

主要优点是您将状态的形状与道具的形状分离。

于 2017-12-28T14:58:00.280 回答