useSelector挂钩在页面重新加载时返回空数组

时间:2020-07-14 17:35:14

标签: reactjs typescript redux

我有一个路由为/properties/details/:id的以下文件。

function App():JSX.Element {
  return (
    <div className="app">
      <Router>  
          <div className="body-container">
             <Switch>
                <Route exact path={['/', '/home']} component={Home}  />
                //...
                <Route exact path="/properties/details/:id" component={PropertyDetails}/>
            </Switch>
          </div>              
      
      </Router>
    </div>
  );
}

export default App;

以下是PropertyDetails组件

import React from 'react';
import  { useDispatch, useSelector} from 'react-redux';
import { RootState } from '../../store/index';
import { Listing } from '../../store/listings/types';
import { Media } from '../../store/listings/types';

const PropertyDetails:React.FC<any> = (props):JSX.Element => {  
  const listings:Listing[] = useSelector<RootState, Listing[]>((state: RootState) => state.listings);
  const id = props.match.params.id;
  const filteredListings:Listing[] = listings.filter((item:Listing) => { 
    if (item.listingId) {
      return item.listingId === id;
    }
  });

  const listing:Listing = filteredListings[0] || { media: []};

  return (
    <div>
      <p>Country : {listing.country}</p>
      <div className="images">
        {       
            listing.media.map((item: Media, index) => { 
            return (<div className="image-container">
              <img key={index} src={item.MediaURL} /> 
            </div>)
            })
          }
      </div>
    </div>
  )
};

export default PropertyDetails;

我能够从以下PropertyList组件和Link的{​​{1}}组件导航到上面的组件

react-router-dom

这是我的动作文件

import React from 'react';
import PropertyItem from '../PropertyItem/PropertyItem';
import { Link } from 'react-router-dom';
import Card from '../Card/Card';
import './PropertyList.scss';

const PropertyList:React.FC<any> = ({ listings }):JSX.Element => { 
  return (
    <div className="property-list">
      {listings.map((item:any) => (        
        <Link to={`/properties/${item.listingId}`}>
            <Card >
              <PropertyItem key={item.listingId} { ...item}/>
            </Card>
        </Link>        
      ))}
    </div>
  );
};

export default PropertyList;

以下是我的减速器

import { Listing, ListingActionTypes, ListingAction } from './types';
import axios from 'axios';

export function fetchListings(listings: Listing[]): ListingAction {
  return {
    type: ListingActionTypes.FETCH_ALL_LISTINGS,
    payload: listings,
  }
}

const axiosInstance = axios.create({
  baseURL: `https://api.example.com`,
});

export function fetchListingsData() {
  const url = `/listings?access_token=${process.env.REACT_APP_API_KEY}`;

  return async (dispatch: { (arg0: ListingAction):void }) => {
    try {
      const res = await axiosInstance({
        method: 'get',
        url: url,
      });

      const data = transformResponse(res);      
      dispatch(fetchListings([...data]));
    } catch(error) {
      console.log(error); //TODO: handle error
    }
    return 'done';
  };
}

const transformResponse = (res: any):Listing[] => {
  if (res && res.data && res.data.bundle) {
    return res.data.bundle.map((item: any) => {
      const weather = {
        //...
        country: item.Country,        
      };
      return weather;
    });
  } else {
    return [];
  }
};

使用链接,我能够成功加载详细信息内容。但是当我刷新页面时,内容消失了。 import { Listing, ListingActionTypes, ListingAction, } from './types'; const initialState:Listing[] = []; export const listings = (state=initialState, action: ListingAction): Listing[] => { switch(action.type) { case ListingActionTypes.FETCH_ALL_LISTINGS: if (action.payload) { state = [...action.payload]; return state; } else { state = []; return state; } default: return state; } } 钩子返回一个空数组。我不确定为什么会这样。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我看不到您在呼叫fetchListingsData()的地方。我假设您正在PropertyList组件上调用它。如果没有可用数据,则需要确保也在PropertyDetails组件上调用该函数。

刷新页面时,内存中的所有数据都会丢失,您必须再次拨打电话以获取数据。