如何在链路中使用redux状态数据?

ifmq2ha2  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(144)

我是redux和reactjs的新手。我正在尝试使用一个名为type的状态数据,我正在使用axios在第17行中获取链接。我正在使用dispatch()从另一个.jsx文件设置type的值。
Home.jsx文件中,我在第24行调用调度程序,以使用onClick事件更新状态值type

主目录.jsx

import React from 'react';
import '../styles/home.scss';
import { Link } from 'react-router-dom';
import { setType } from '../redux/imageSlice';
import { useDispatch } from 'react-redux';

const Home = () => {
  const dispatch = useDispatch();

  return (
    <div className="container">
      <div className="row">
        <div className="col-sm-6 col-md-4 d-flex justify-content-center my-3">
          <div className="ci">
            <img
              className="img-fluid"
              src="https://res.cloudinary.com/djz3p8sux/image/upload/v1662295247/web-projects-images/natures_hodrkk.jpg"
              alt="Nature"
            />
            <Link to="/nature">
              <div className="middle">
                <div
                  className="text"
                  onClick={() => dispatch(setType('nature'))}>
                  Nature
                </div>
              </div>
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Home;

图像切片.js

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

const initialState = {
  type: '',
  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=${initialState.type}&per_page=15`,
    {
      headers: config,
    }
  );
  return res.data;
});

export const imageSlice = createSlice({
  name: 'images',
  initialState,
  reducers: {
    setType: (state, action) => {
      state.type = action.payload;
    },
  },
  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 { setType } = imageSlice.actions;

export default imageSlice.reducer;

存储.js

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

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

如何做到这一点?我正在尝试更新获取链接使用状态类型值在第17行在imageSlice.js文件。

mqxuamgl

mqxuamgl1#

一个选项是通过参数将类型提供给fetchImages(请参见payload):

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

然后,在调用fetchImages时,需要为函数提供类型。下面是一个示例组件:

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

function YourCallingComponent(props) {
    const dispatch = useDispatch();
    const currentType = useSelector((state) => state.type);

    function fetchImagesOfType() {
        dispatch(fetchImages({
            type: currentType
        }));
    }

    return (
    ...
    )
}

相关问题