我正在学习Redux,在下面的应用程序中,我没有在App.js中得到“列表”,有人能告诉我出了什么问题吗?

sshcrbum  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(127)

我正在学习Redux,这里我试着构建一个简单的应用来理解这个概念,为什么我不能在App.js中获得列表呢?我已经通过dispatch从index.js传递了它,我试着在App.js的useEffect中接收它。

索引.js

我将mockData作为清单从index.js传递到App.js

import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';

import App from './App';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

const mockData = [
  {
      name: "Barry Johnson",
      age: 43,
  },
  {
      name: "Chris Evan",
      age: 25,
  },
];
const getAll = () => {
  return mockData;
};

const listingsReducer = (state = [], action) => {
  switch (action.type) {
      case 'INIT_LISTINGS':
          return action.data;
      default:
          return state;
  }
};
export const initListings = () => {
  return async dispatch => {
     const listings = await getAll();
     dispatch({
         type: 'INIT_LISTINGS',
         data: listings,
     });
  };
};

const store = createStore(listingsReducer, applyMiddleware(thunk));

root.render(
  <StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </StrictMode>
);

应用程序js

在useEffect中,我记录了清单,但没有定义。

import React from "react";
import "./style.css";
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { initListings } from './index.js';

export default function App() {
  const dispatch = useDispatch();
  const listings = useSelector((state) => state.listings)

  useEffect(() => {
    dispatch(initListings());
    console.log(listings);
  }, [dispatch]);

  return (
    <div>
      <div className="App">
        <p>Start editing to see some magic happen :)</p>
      </div>
    </div>
  );
}
k10s72fa

k10s72fa1#

在您的reducer函数中,使用以下列表是您的reducer函数:-

const listingsReducer = (state = {}, action) => {
  switch (action.type) {
      case 'INIT_LISTINGS':
          return {...state, listings : action.payload};
      default:
          return state;
  }
};

相关问题