簡體   English   中英

ReactJs:從 redux-store 獲取數據

[英]ReactJs: get data from redux-store

我創建組件,將其連接到 redux,初始化 state 並創建減速器。

零件:

import fetchReducer from './reducers/fetchReducer';
import initialState from './constants/initialState';

const store = createStore(fetchReducer, initialState, devToolsEnhancer());

class Table extends React.Component {
  // constructor

   getDataFromState = function () {
      let propsContent = this.props;
      let itemsStored = propsContent.itemsProp;
      return itemsStored;
     };

   getOperationItems = function () {
      let itemsStored = this.getDataFromState();
      itemsStored.map((item, index) => (
          <li> key={index} item={item}</li>
       ))};

   render() {
       return (
           <div className={styles}>
               {this.getOperationItems()}
           </div>
         );
     }
 }

 const mapStateToProps = (store) => {
     return {itemsProp: store.items}
  };

 export default connect(mapStateToProps)(Table)

ReactDOM.render(
   <Provider store={store}>
       <Table/>,
    </Provider>,
   document.getElementById("app")
);

初始 state:

export default {
   items: [
      {
        'Date': 1,
        'Operation': 1
       }
     ]
 }

減速器:

 import initialState from '../constants/initialState';

 export default function update(state = initialState) {
           return state;
  }

但我無法從商店獲取初始數據。 調試時,我在 Table#getDataFromState 方法中看到 propsContent 包含空 ({}) 數組 - 而不是預期的 [{'Date': 1,'Operation': 1 }]。

調試我也看到了,reducer 收到初始 state 和正確的數據:[{'Date': 1,'Operation': 1}]

你如何注冊傳遞給createStore的reducer? 在 mapStateToProps 中使用它很重要:

您可以在此處查看有關如何注冊減速器的示例

更新

問題是您如何使用連接的組件Table 如果您在另一個文件中定義它然后導入它,您的代碼可以完美運行,如您在此處看到的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM