【发布时间】:2018-06-08 22:56:43
【问题描述】:
我不确定这是否是正确的做事方式,或者是否有可能,因此我的问题在这里。
我在我的项目中使用 react-redux、redux-thunk、json-server(用于虚拟数据)和 typescript。通过 1 个 api 调用,我用我的应用程序的所有数据更新了“数据”reducer。这些数据通过 combineReducers 与其他 reducer 一起使用: Redux tree
我想做的是将 data.labels 作为道具映射到我的组件中。一旦整个 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 store 中的结构,以 '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
-
我认为您发送的标签数据与之前的数据相同。因此,componentWillReceiveProps 不会触发。
-
可以分享一下你正在使用的props界面吗?
-
@brub 谢谢你!似乎是一个有趣的想法,所以我会试一试!
-
@metinata 更新了我的帖子,有日志显示前后数据有差异,所以我认为应该触发方法?
标签: reactjs typescript redux react-redux json-server