如何使用 React 在我的前端 UI 上显示我的 API 响应消息?

How can I display my API response message on my frontend UI with React?

我有一个 Upload 组件,在向我的 API 提交并完成请求后,returns 一条消息(来自后端)并且我有一个状态 const [data, setData] = useState(); 我正在利用它来存储消息。如果可能的话,我想知道如何将此消息显示为 h1 或 p 元素。我以前做过,但这个实现有点不同,我需要帮助。下面是消息和代码。

Upload.jsx:

import '../../components/pages/styles/Uploads.css';
import {useEffect, useState} from 'react';
import {} from 'react-router-dom';
import {useDispatch, useSelector} from 'react-redux';
import axios from 'axios';
import authHeader from '../../services/auth-header';
import {useForm} from 'react-hook-form';
import {clearMessage} from '../../slices/messages';
const API_URL = 'http://localhost:8080/api/posts';

function Uploads() {
    const {user: currentUser} = useSelector((state) => state.auth);
    const [successful, setSuccessful] = useState(false);
    const {message} = useSelector((state) => state.message);
    const dispatch = useDispatch();
    const {
        register,
        handleSubmit,
        watch,
        formState: {errors},
    } = useForm();
    //console.log(watch('title'));

    const [file, setFile] = useState();
    const [title, setTitle] = useState();
    const [preview, setPreview] = useState(null);
    const [data, setData] = useState();

    useEffect(() => {
        dispatch(clearMessage());
    }, [dispatch]);

    const onAddImage = (file) => {
        window.URL.revokeObjectURL(preview);
        if (!file) return;
        setPreview(window.URL.createObjectURL(file));
        setFile(file);
    };
    const onSubmit = async () => {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('title', title);
        console.log(file);

        axios
            .post(API_URL + '/upload', formData, {
                headers: {...authHeader(), 'Content-Type': 'multipart/form-data'},
            })
            .then((res) => setData(res.data));
    };

    return (
        <div className='page'>
            <div className='upload-card'>
                <div id='preview'>
                    <img
                        src={preview || require('../../assets/user-solid.jpeg')}
                        id='image'
                        alt='Thumbnail'
                        className='user-post'
                    />
                </div>
            </div>
            <div className='upload-container'>
                <div className='post-form-container'>
                    <p id='upload-form-label'>Hello, feel free to post an image!</p>
                    <form onSubmit={handleSubmit(onSubmit)} className='upload-form'>
                        <div className='panel'>
                            <div className='button_outer'>
                                <div className='btn_upload'>
                                    <input
                                        {...register('file', {required: true})}
                                        filename={file}
                                        onChange={(e) => onAddImage(e.target.files[0])}
                                        type='file'
                                        accept='.jpeg,.svg,.gif,.png'
                                        id='image-selection-btn'
                                        name='file'
                                    ></input>
                                    Choose your Art
                                </div>
                            </div>
                            {errors.file?.type === 'required' && (
                                <p className='alert alert-danger' id='file-error'>
                                    File is required
                                </p>
                            )}
                        </div>
                        <input
                            {...register('title', {required: true})}
                            type='text'
                            onChange={(e) => setTitle(e.target.value)}
                            className='form-control'
                            placeholder='Title'
                        />
                        {errors.title?.type === 'required' && (
                            <p className='alert alert-danger' id='title-error'>
                                Title is required
                            </p>
                        )}

                        <button type='submit' id='post-upload-btn'>
                            Upload Image
                        </button>
                    </form>
                </div>
        {/* need help here */}
                {data && (
                    <div className='form-group'>
                        <div
                            className={data ? 'alert alert-success' : 'alert alert-danger'}
                            role='alert'
                        >
                            {message}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}

export default Uploads;

我以前使用过消息状态,但我不知道这次如何使用它,或者是否有必要使用它,因为它已经存储在 data.

messages.js:

// This updates message state when message action is dispatched from anywhere in the application. It exports 2 action creators:

// setMessage
// clearMessage

import {createSlice} from '@reduxjs/toolkit';
const initialState = {};
const messageSlice = createSlice({
    name: 'message',
    initialState,
    reducers: {
        setMessage: (state, action) => {
            return {message: action.payload};
        },
        clearMessage: () => {
            return {message: ''};
        },
    },
});
const {reducer, actions} = messageSlice;
export const {setMessage, clearMessage} = actions;
export default reducer;

如果将 setData(res.data) 替换为 console.log(res.data) 会产生您期望呈现的 message

{ message: 'File Upload Successful' }

那么我认为您在 data 状态下拥有您需要的一切。

{data && (
  <div className='form-group'>
    <div
      className={data ? 'alert alert-success' : 'alert alert-danger'}
      role='alert'
    >
      {data.message}
    </div>
  </div>
)}