簡體   English   中英

ReactJs:從父組件 URL 獲取數據並將其傳遞給子組件

[英]ReactJs: Get data from parent URL and pass it to child component

我正在從 reactjs 中的表單發送表單數據。 來自用戶的一些預先輸入必須與表單一起發送。 我從父文件的 URL 中獲取該數據,並且表單位於子組件中。

父 url: http://localhost:3000/uploadlist?phmcy=2

我必須從 URL 中獲取 phmcy 值。 (這里必須傳遞的數據是'2')。

父組件:

import Upload froimportm './Upload'
import axios from "axios";
import { Link, withRouter } from "react-router-dom";
import { useLocation } from 'react-router';

export default function Uploadlist() {
    let phmcy = (new URLSearchParams(window.location.search)).get("phmcy")

    var myphmcy = JSON.stringify(phmcy);
    //const phmcyvalue = new URLSearchParams(this.props.location.search);
    //const phmcy = phmcyvalue.get('phmcy')
    console.log(myphmcy);


    const ordersAPI= (url='https://localhost:44357/api/Orders') => {
        return {
            fetchAll: () => axios.get(url),
            create: newRecord => axios.post(url, newRecord),
            update: (id, updateRecord) => axios.put(url + id, updateRecord),
            delete: id => axios.delete(url+id)
        }
    }
 
    const addOrEdit = (formData, onSuccess) => {

        ordersAPI().create(formData)
        .then(res => {
            onSuccess();
        })
        .catch(err => console.log(err.response.data))
    }

    return (
        <div className="row">
            <div className="jumbotron jumbotron-fluid py-4 "></div>
            <div className="container text">
                <h1 className="display-4"> Order Register</h1>
            </div>
            <div className="col-md-4 offset-3">
                <Upload
                    addOrEdit = {addOrEdit}
                    myphmcy = {myphmcy}
                />
                </div> 
                <div className="col-md-1">
                    <div> </div>
                </div>
            
        </div>
    )
}

子組件:(這是表單所在的位置。我只包含了一部分)

import React, {useState, useEffect} from 'react';


import  myphmcy from './Uploadlist';

//const myphmcy = JSON.stringify(phmcy);
console.log(myphmcy);
const defaultImageSrc = '/images/7.jpg';


const initialFieldValues ={
    orderId:0, 
    dateTime:'',
    status:'',
    status2:'',
    pharmacyName:'',
    customerName:'',
    patientName:'',
    patientAge:'',
    address:'',
    email:'',
    teleNo:'',
    customerId:1,
    pharmacyId:myphmcy,//data obtaind from the URL have to posted as the pharmacyID when posting. 
    imageName:'',
    imageSrc:'',
    imageFile: null
    
}


export default function Upload(props) {

    const {addOrEdit} = props

    const {myphmcy} = props

    const [values, setValues] = useState(initialFieldValues)
    const[errors, setErrors] = useState({})

    const handleInputChange= e => {
        const {name, value} = e.target;
        setValues({
            ...values,
            [name]:value
        })
        
    }

    const showPreview = e => {
        if(e.target.files && e.target.files[0]){
            let imageFile = e.target.files[0];
            const reader = new FileReader();
            reader.onload = x => {
                setValues({
                    ...values,
                    imageFile,
                    imageSrc : x.target.result
                    
                })
                
            }
            reader.readAsDataURL(imageFile)
        }

        else{
            setValues({
                ...values,
                imageFile:null,
                imageSrc:''
            })
        }

    }

    const validate = () => {
        let temp = {}
        temp.customerName = values.customerName == "" ? false : true;
        setErrors(temp)
        return Object.values(temp).every(x => x == true)
    }

    const resetForm = () => {
        setValues(initialFieldValues)
        document.getElementById('image-uploader').value = null;
    }

    const handleFormSubmit = e => {
        e.preventDefault()
        if (validate()){
        
        const formData = new FormData()
        
        formData.append('orderId',values.orderId)
        formData.append('dateTime',values.dateTime)
        formData.append('status',values.status)
        formData.append('status2',values.status2)
        formData.append('pharmacyName',values.pharmacyName)
        formData.append('customerName',values.customerName)
        formData.append('patientName',values.patientName)
        formData.append('patientAge',values.patientAge)
        formData.append('address',values.address)
        formData.append('email',values.email)
        formData.append('teleNo',values.teleNo)
        formData.append('customerId',values.customerId)
        formData.append('pharmacyId',values.pharmacyId)
        formData.append('imageName',values.imageName)
        formData.append('imageFile',values.imageFile)
        addOrEdit(formData, resetForm) 

        alert("Your file is being uploaded!")
    }
}

const applyErrorClass = field => ((field in errors && errors[field] == false) ? ' invalid-field' : '')


    

    return (
        <>
        <div className="container text-center ">
            <p className="lead"></p>
        </div>
        <form autoComplete="off" noValidate onSubmit={handleFormSubmit}>
            <div className="card">
                <div className="card-header text-center">Place Your Order Here</div>
            
            <img src={values.imageSrc} className="card-img-top"/>

                <div className="card-body">

                    <div className="form-group">
                        <input type="file" accept="image/*" className="form-control-file" onChange={showPreview} id="image-uploader"/> 
                    </div>
                    <div className="form-group">
                        <input type="datetime-local" className="form-control" placeholder="Date Time" name="dateTime" value={values.dateTime}
                       onChange={ handleInputChange}/>
                    </div>

                    <div className="form-group">
                        <input className="form-control" placeholder="Enter the prescription items and qty" name="status" value={values.status} onChange={ handleInputChange}/>
                    </div>

                    <div className="form-group">
                        <input className="form-control" placeholder="What are the symptoms?" name="status2" value={values.status2} onChange={ handleInputChange}/>
                    </div>

                    <div className="form-group">
                        <input className="form-control" placeholder="Pharmacy Name" name="pharmacyName" value={values.pharmacyName} onChange={ handleInputChange}/>
                    </div>

                    <div className="form-group">
                        <input className={"form-control" + applyErrorClass('customerName')}  placeholder="Your Name" name="customerName" value={values.customerName} onChange={ handleInputChange}/>
                    </div>

                    <div className="form-group">
                        <input className="form-control" placeholder="Patient Name" name="patientName" value={values.patientName} onChange={ handleInputChange}/>
                    </div>

                    <div className="form-group">
                        <input className="form-control" placeholder="Patient Age" name="patientAge" value={values.patientAge} onChange={ handleInputChange}/>
                    </div>

                    <div className="form-group">
                        <input className="form-control" placeholder="Delivery address" name="address" value={values.address} onChange={ handleInputChange}/>
                    </div>

                    <div className="form-group">
                        <input className="form-control" placeholder="Your Email" name="email" value={values.email} onChange={ handleInputChange}/>
                    </div>

                    <div className="form-group">
                        <input className="form-control" placeholder="Contact Number" name="teleNo" value={values.teleNo} onChange={ handleInputChange}/>
                    </div>

                    <div className="form-group text-center">
                        <button type="submit" className="btn btn-light">submit</button>
                        
                    </div>
                    

                </div>
            </div>
        </form>
    </>
    )
}

這效果不好,我無法發布數據。 有天才能幫我解決這個問題嗎?

問題

出於某種原因,您導入Uploadlist (默認導出/導入)並將其命名為myphmcy ,將其保存在初始 state 中,然后永遠不要使用傳遞的myphmcy 這種模式往往會導致 state 過時,因為您還需要在 prop 值更新時進行處理,以便您可以同步 state 值。

解決方案

存儲傳遞的 props 在 React 中是反模式的,只需在handleFormSubmit提交處理程序中直接使用myphmcy prop。 這確保您在提交表單數據時始終使用最新的myphmcy props 值。

const handleFormSubmit = e => {
    e.preventDefault();
    if (validate()) {
    
    const formData = new FormData();
    
    formData.append('orderId', values.orderId);
    formData.append('dateTime', values.dateTime);
    formData.append('status', values.status);
    formData.append('status2', values.status2);
    formData.append('pharmacyName', values.pharmacyName);
    formData.append('customerName', values.customerName);
    formData.append('patientName', values.patientName);
    formData.append('patientAge', values.patientAge);
    formData.append('address', values.address);
    formData.append('email', values.email);
    formData.append('teleNo', values.teleNo);
    formData.append('customerId', values.customerId);
    formData.append('pharmacyId', myphmcy) // <-- use the prop directly
    formData.append('imageName', values.imageName);
    formData.append('imageFile', values.imageFile);
    addOrEdit(formData, resetForm) ;

    alert("Your file is being uploaded!");
};

您從道具中獲取 myphmcy 值,但將其設置在 function 之外。 所以它只會將 undefined 設置為 pharmacyId。 您需要在函數內分配 myphmcy 值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM