javascript - 使用 react usestate 钩子将 values 存储在数组中

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

所以我想在 uploadedFileCategory 数组中 store value 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)

回答1

让我回答这个问题:

问题一:

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 代码编辑器告诉我 UploadFileCategory 已声明,但它的 value 永远不会被读取。ts(6133)

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

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

相似文章

随机推荐

最新文章