【问题标题】:How to pass data from parent to child (react Modal)?如何将数据从父母传递给孩子(反应模态)?
【发布时间】:2022-09-26 01:09:30
【问题描述】:

我有一个页面用户.jsx(父)和一个组件DialogEditUser.jsx(孩子)我想通过它的id(使用find方法)将位于父母中的用户的特定数据传递给孩子

这个传递的数据应该作为一个值加载到反应模式中的输入。

用户.jsx代码:

import React, { useState, useEffect } from \'react\'
import DialogAddUser from \'src/components/DialogAddUser\'
import { getUsers} from \'src/Service/api\'

const Typography = () => {
  const [users, setUsers] = useState([])

  useEffect(() => {
    getAllUsers()
  }, [])

  const deleteUserData = async (id) => {
    setConfirmDialog({
      ...setConfirmDialog,
      isOpen: false,
    })
    await deleteUser(id)
    getAllUsers()
    setNotify({
      isOpen: true,
      message: \'Article Deleted Successfully.\',
      type: \'error\',
    })
  }

  const getAllUsers = async () => {
    let response = await getUsers()
    setUsers(response.data)
    console.log(response.data)
  }
return ( //... )

DialogEditUsers.jsx代码:

import { useEffect, useState } from \'react\'
import { getUsers, editUser } from \'../Service/api\'

const initialValue = {
  id: \'\',
  code: \'\',
  article: \'\',
  price: \'\',
  vat: \'\',
  status: \'\',
  company_id: \'\',
}

export default function DialogAddUser() {
  const [user, setUser] = useState(initialValue)
  const { code, article, price, vat, status, company_id } = user

  const normalize = (v) => ({
    code: v.code,
    article: v.article,
    price: Number(v.price),
    vat: Number(v.vat),
    status: Number(v.status),
    company_id: Number(v.company_id),
  })

  useEffect(() => {
    loadUserDetails()
  }, [])

  const loadUserDetails = async () => {
    const response = await getUsers(id)
    console.log(\'loading user details \', response)
    setUser(response.data.find((x) => x.id == id))
  }

  const editUserDetails = async () => {
    const response = await editUser(id, normalize(user))
    console.log(\'Edit user details \', response)
  }

  const onValueChange = (e) => {
    console.log(e.target.value)
    setUser({ ...user, [e.target.name]: e.target.value })
  }
return (
    <>
      <CModal
        visible={visible}
        onClose={() => setVisible(false)}
        backdrop={\'static\'}
        keyboard={false}
        portal={false}
      >
        <CModalHeader>
          <CModalTitle>Edit Article:</CModalTitle>
        </CModalHeader>
        <CModalBody>
          <CForm>
            <CFormInput
              type=\"text\"
              id=\"exampleFormControlInput1\"
              label=\"Code :\"
              placeholder=\"Enter Code\"
              text=\" \"
              aria-describedby=\"exampleFormControlInputHelpInline\"
              onChange={(e) => onValueChange(e)}
              value={code}
              name=\"code\"
            />
            <CFormInput
              type=\"text\"
              id=\"exampleFormControlInput2\"
              label=\"Article :\"
              placeholder=\"Enter Article\"
              text=\" \"
              aria-describedby=\"exampleFormControlInputHelpInline\"
              onChange={(e) => onValueChange(e)}
              value={article}
              name=\"article\"
            />
//...the rest of inputs...

api.js代码:

import axios from \'axios\'

const baseURL = \'https://api.factarni.tn/article\'

const token =
  \'eyJhbGciOiJSUzI1NiIsImtpZCI6IjIxZTZjMGM2YjRlMzA5NTI0N2MwNjgwMDAwZTFiNDMxODIzODZkNTAiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoiZmFraHJpIGtyYWllbSIsInBpY3R1cmUiOiJodHRwczovL2xoMy5nb29nbGV1c2VyY29udGVudC5jb20vYS9BSXRidm1uMS12dWJJcHNxTURKMkNTcDhVcTlmU3I1LUI1T3Y3RHY2SFRNMT1zMTMzNyIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9mYWN0YXJuaSIsImF1ZCI6ImZhY3Rhcm5pIiwiYXV0aF90aW1lIjoxNjYzNzY3ODk5LCJ1c2VyX2lkIjoiaWhqM0JWM0hIRFhpVnUwdmpzV3ZidjMyRDdMMiIsInN1YiI6ImloajNCVjNISERYaVZ1MHZqc1d2YnYzMkQ3TDIiLCJpYXQiOjE2NjM3Njc4OTksImV4cCI6MTY2Mzc3MTQ5OSwiZW1haWwiOiJmYWtocmlpLmtyYWllbUBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJnb29nbGUuY29tIjpbIjEwODU1MTA3MjAwODIwNjMxMjI0NCJdLCJlbWFpbCI6WyJmYWtocmlpLmtyYWllbUBnbWFpbC5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJnb29nbGUuY29tIn19.bvRTxHfPtJrQjF2BjXqhs7ji738kma55LMFVRb8jkeraWP-JRBi-LRPa0d7OR_-BPwCGuRBXIb6980_PP8wjhBeDdB5B77GujiGn3nUvpPOFeIaM0L7muw1NKo4YCtS3v6ifuywypTbL3_5x3SBFZEH-QV0sp5DAzaA-P3Fn8AwP66o3cUPHGengGpZNsfkJ0FYcqzH-xpyKVVWV\'
//i dont mind sharing this token, it\'s for you to test this code if you need.

const config = { headers: { Authorization: `Bearer ${token}` } }

export const getUsers = async (id) => {
  id = id || \'\'
  try {
    return await axios.get(`${baseURL}`, config)
  } catch (error) {
    console.log(\'Error while calling getArticles api \', error)
  }
}

export const editUser = async (id, user) => {
  return await axios.put(`${baseURL}/${id}`, user, config)
}

我使用上面的代码进入终端的唯一节点错误(因为我不知道如何传递指定用户的正确 ID)是:

src\\components\\DialogEditUser.jsx
  Line 45:37:  \'id\' is not defined  no-undef
  Line 47:47:  \'id\' is not defined  no-undef
  Line 51:37:  \'id\' is not defined  no-undef

为了更好地解释问题(我不知道如何使用在线sn-ps对不起):

所以我期待什么是:当我单击编辑按钮时,我应该在每个输入中获得一个带有用户数据(codearticlepricevatstatuscompany_id)的表单作为值的形式,就像下面的这个 gif:

此外,用户页面中的console.log(response.data) 显示:

    标签: reactjs modal-dialog react-props


    【解决方案1】:

    几天前我也面临同样的问题。我的解决方案是在父组件中创建状态并将状态传递给子组件。它的例子-

    家长班

    const parent= ()=>{
    const [name, setName]= useState('')
    const [password, setPassword]= useState('')
    return(
    <Child setName={setName} setPassword={setPassword} />
    )
    }
    

    儿童班

    const Child = ({setPassword,setName})=>{
    return(
    <div>
    <input type="text" placeholder="Enter Name" onChange={(e)=>setPassword(e.target.value)} />
    <input type="text" placeholder="Enter Name" onChange={(e)=>setPassword(e.target.value)} />
    </div>
    )
    }
    

    希望我的回答能帮助您解决问题,如果您仍然面临问题,请让我知道我会帮助您。

    【讨论】:

    • 我按照你的例子,试图通过这种方式将数据作为道具传递,但它没有用。我遇到了新错误 (Cannot destructure property 'code' of 'user' as it is undefined. DialogEditUsers.jsx :15)
    • 然后在父级中再创建一个用户状态并将其传递给子级。另外请删除 api 代码的重要凭据。
    • 我很挣扎,无法解决它.. :(
    • 等等,让我为你重写整个代码......
    • 完成请检查...
    猜你喜欢
    • 2020-04-06
    • 2020-09-19
    • 2021-10-31
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2020-10-31
    • 2022-11-21
    • 2018-03-29
    相关资源
    最近更新 更多