繁体   English   中英

使用 react usestate hook 将值存储在数组中

[英]storing values in an array using react usestate hook

我有以下基于 formik 的示例,其中我正在使用 primereact fileupload。 每次用户上传文件时, selectedAssetCategoryId的值都是不同的。 如果用户一次上传多个文件,则该值将保持不变。 例如,如果用户同时上传 3 个文件,则selectedAssetCategoryId的值将为 1。

所以我想在uploadedFileCategory数组中存储值1三次。

setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]); 将项目放入数组的正确方法? 当我将鼠标悬停在const [uploadedFileCategory, setUploadedFileCategory] = useState([])这一行的变量uploadedFileCategory上时,visual studio 代码编辑器告诉我uploadedFileCategory is declared but its value is never read.ts(6133)

const DataRequestForm = (props) => {
    const user = JSON.parse(sessionStorage.loggedInUser)
    const {values, setFieldValue, touched, errors, isSubmitting, handleReset, handleChange} = props;
    const growl = React.createRef()
    
     const [uploadedFileCategory , setUploadedFileCategory] = useState([])

    
    
    // fileUpload function testing using new service
    const fileUpload = (e) => {
      

         //Store the values in an array.
         setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]);
      
        const personnelId = JSON.parse(sessionStorage.loggedInUser).id
        let formData = new FormData();
        e.files.forEach((file, i) => formData.append(`files`, file))

        axios.post('upms/uploadAndCreateAssociations?personnelId=' + personnelId +'&assetCategoryId='+selectedAssetCategoryId, formData,{
            headers: {
                "Content-Type": "multipart/form-data"
            }
        }).then((response) => {
            
            }).catch(err => console.log(err));


        }).catch((response) => {
            growlComp.show({severity: 'error', summary: 'File Upload unsuccessful', detail: 'File Upload was unsuccessful'})
            console.log('Could not upload files.....')
        })
      
    }
    

    

     
    
    

    return (
        <div>
            
            <div id="formDiv">
                <Growl ref={growl}/>
                <Form className="form-column-3">
                                         
                         
                    <div className="datarequest-form">   
                     <label style={{marginRight: '1355px',fontWeight: 'bold'}}>Document Upload</label>
                   
                    <div className="form-field">
                                <FileUpload
                                    name="files"
                                    mode='advanced'
                                    uploadHandler={fileUpload}
                                    customUpload={true}
                                    chooseLabel="Attach Files"
                                    maxFileSize="2058722381"
                                    ref={fileUploadRef}
                                    id="researcherAttachFileButton"
                                    disabled={disableButton}
                                    multiple={true}/>   
                                   
                             </div>

                       
                      
                       
                    </div>
                </Form>
            </div>
        </div>
    )

};

export const DataRequestEnhancedForm = withFormik(
    
    
    
    {

        
    mapPropsToValues: props => {

              
        
        return {
            
            uploadedFileCategory: uploadedFileCategory
            
        }
    },
    validationSchema:validationSchema,
    handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
      
        props.handleSubmit(values)
      
        setSubmitting(false)
    },
    setFieldValue(field, value, shouldVal) {
        console.log('In setFieldValue')
    },

    displayName: 'Data Request Form',
})(DataRequestForm)

让我回答这个问题:

问题一:

setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]); 将项目放入数组的正确方法?

答案它有效,这里是示例代码:

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [array, setArray] = useState([]);
  const changeArray = () => {
    console.log(array);
    setArray((b) => [...array, 1]);
  };
  return (
    <div className="App">
      <h1>Open console to see the logs</h1>
      <button onClick={() => changeArray()}>Example</button>
    </div>
  );
}

该链接当前位于: https://byy0g5.csb.app/查看控制台以查看日志。

问题2

当我将鼠标悬停在 const [uploadedFileCategory, setUploadedFileCategory] = useState([]) 这一行的变量 uploadedFileCategory 上时,visual studio 代码编辑器告诉我 uploadedFileCategory 已声明,但其值从未被读取。ts(6133)

Answer它只是意味着uploadedFileCategory没有在代码中的任何地方使用。

即使正确设置了值,您也需要将其正确放置在代码中才能看到值的变化。 尝试console.log(uploadedFileCategory)查看代码的 output。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM