網站搜尋

reactjs - 使用 API 資料時 React-Redux 的 componentWillReceiveProps 未觸發


我不確定這是否是正確的做事方式,或者是否甚至可能,因此我在這裡提出我的問題。

我在我的專案中使用 react-redux、redux-thunk、json-server(用於假資料)和 typescript。透過一次 API 呼叫,我更新了用於整個應用程式的 'data' reducer。這些資料會與其他 reducers 一起通過 combineReducers 使用:Redux 樹狀結構

我想要做的是把 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

有什麼建議可以讓這個運作,而不需要把整個資料物件作為 prop 傳入嗎?

編輯

在使用完整的 'data' 情況下,當在 data 還未被抓取時,我在 componentWillReceiveProps 中記錄 data.labels,會得到一個空的標籤陣列。資料成功抓取後,我的日誌會顯示一個包含 x 個標籤的陣列。

以下是我使用的介面:資料介面(redux 儲存中的結構,以 'data' 為父層):

interface Data {
  labels: Label[];
  defaultLinks: DefaultLink[];
  customLinks: CustomLink[];
  request: boolean;
  failure: boolean;
}

我組件中使用的 Props 介面:

interface Props {
  labels: Label[];
  ...; // Other stuff
}

答案#1

你可能正在尋找選擇器模式:gist.github.com/abhiaiyer91/aaf6e325cf7fc5fd5ebc70192a1fa170,通常與 reselect 一起使用:github.com/reactjs/reselect#reselect

主要的優點是你可以將狀態的形狀與屬性的形狀分離開來。