我不确定这是否是正确的做事方式,或者是否可能,因此我的问题在这里。
我在我的项目中使用了react-redux、redux-thunk、json-server(用于虚拟数据)和typescript。通过 1 个 api 调用,我使用应用程序的所有数据更新“数据” reducer 。该数据通过combineReducers 与其他reducer 一起使用: Redux tree
我想做的是将 data.labels 作为 prop 映射到我的组件中。一旦整个 api 调用完成,并且 data.labels 被填充,我想向我的前端显示这些数据。然而,我注意到当我的数据 api 调用完成时,根本不会触发 componentWillReceiveProps。如果我将整个“data”属性而不是“data.labels”附加到我的组件,它会更新。
reducer :
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
关于如何在不将整个数据对象作为 prop 注入(inject)的情况下使其工作的任何提示?
编辑
在使用完整“数据”的情况下,在获取数据之前在 componentWillReceiveProps 中记录 data.labels 时,我会得到一个空标签数组。成功获取数据后,我的日志显示 x 个标签的数组。
以下是我使用的接口(interface): 数据接口(interface)(redux store 内部的结构,以“data”为父级):
interface Data {
labels: Label[];
defaultLinks: DefaultLink[];
customLinks: CustomLink[];
request: boolean;
failure: boolean;
}
我的组件中使用的 Props 接口(interface):
interface Props {
labels: Label[];
...; // Other stuff
}
最佳答案
您可能正在寻找选择器模式:gist.github.com/abhiaiyer91/aaf6e325cf7fc5fd5ebc70192a1fa170通常与重新选择结合使用:github.com/reactjs/reselect#reselect
主要优点是您可以将状态的形状与 Prop 的形状分离。
关于reactjs - React-Redux componentWillReceiveProps 未使用 api 数据触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006705/