I have an Upload component that after submitting and completing the request to my API, returns a message (from the backend) and I have a state const [data, setData] = useState(); that I am utilizing to store the message. I would like to know how I can display this message as an h1 or p element if it's possible. I have done it previously before but this implementation is a bit different and I need help. Here is the message and the code below. enter image description here

上载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中.

信息.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>
)}

Javascript相关问答推荐

Vue v模型检测父参考更改

IOS(React Native)中未找到模块SquareReaderSDK

类型错误:tasks.map不是函数(MERN堆栈)

Toast函数找不到其dis

使用Apps Script缩短谷歌表中的URL?

如何循环访问对象数组并以关键值形式获得结果?

创建私有JS出口

如何通过onClick为一组按钮分配功能;

一次仅播放一个音频

为什么从liveWire info js代码传递数组我出现错误?

如何使用侧边滚动按钮具体滚动每4个格?

传递一个大对象以在Express布局中呈现

拖放仅通过 Select 上传

自定义高图中的x轴标签序列

如何从调整大小/zoom 的SVG路径定义新的d属性?""

如何在模块层面提供服务?

如何使用JS创建一个明暗功能按钮?

在开发期间,Web浏览器如何运行&qot;.jsx&qot;文件?

令牌JWT未过期

构建器模式与参数对象输入