axios 为什么刷新页面后得到未定义的结果表单api?

bttbmeg0  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(130)

我是一个初学者,并试图使一个照片画廊。我使用pexels api来获取照片。当我第一次写代码的获取图像,我得到的结果是正确的。但如果刷新页面,我得到未定义。我检查了错误状态,它是空的。实际上,事情发生时,我Map的图像。但如果我注解掉Map代码,然后在控制台上获得照片,没有任何错误。

以下是一段视频:Problem video | Gdrive
图像切片.js

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';

const initialState = {
  images: [],
  error: null,
  isLoading: false,
};

const config = {
  Authorization: '563492ad6f91700001000001350d302e175b4c208aac413953d6edcc',
};

export const fetchImages = createAsyncThunk('images/fetchImages', async () => {
  const res = await axios.get(
    'https://api.pexels.com/v1/search?query=nature&per_page=15',
    {
      headers: config,
    }
  );
  console.log('Axios:', res.data);
  return res.data;
});

export const imageSlice = createSlice({
  name: 'images',
  initialState,
  extraReducers: builder => {
    builder.addCase(fetchImages.pending, state => {
      state.isLoading = true;
    });
    builder.addCase(fetchImages.fulfilled, (state, action) => {
      state.isLoading = false;
      state.images = action.payload;
      state.error = null;
    });
    builder.addCase(fetchImages.rejected, (state, action) => {
      state.isLoading = false;
      state.images = [];
      state.error = action.error.message;
    });
  },
});

// export const {} = imageSlice.actions;

export default imageSlice.reducer;

存储.js

import { configureStore } from '@reduxjs/toolkit';
import imageReducer from './imageSlice';

export const store = configureStore({
  reducer: {
    images: imageReducer,
  },
});

图像.jsx

import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchImages } from '../redux/imageSlice';
import Image from './Image';

const Images = () => {
  const { photos } = useSelector(state => state.images.images);
  const a = useSelector(state => console.log(state.images));

  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(fetchImages());
  }, []);

  return (
    <div className="container">
      <h2>Images</h2>
      {photos.map(photo => (
        <Image key={photo.id} image={photo} />
      ))}
    </div>
  );
};

export default Images;

图像.jsx

import React from 'react';

const Image = props => {
  return (
    <div>
      <div className="row">
        <div className="col">
          <img src={props.image.src.medium} alt={props.image.alt} />
        </div>
      </div>
    </div>
  );
};

export default Image;

为什么会发生这种情况?我该如何解决这个问题?

c9qzyr3d

c9qzyr3d1#

只要改变

return (
        <div className="container">
          <h2>Images</h2>
          {photos.map(photo => (
            <Image key={photo.id} image={photo} />
          ))}
        </

div>
  );

收件人:

return (
    <div className="container">
      <h2>Images</h2>
      {photos && photos.map(photo => (
        <Image key={photo.id} image={photo} />
      ))}
    </div>
  );

相关问题