如何将从数据库接收的数据作为道具传递到Reactjs中的另一个组件

问题描述 投票:0回答:2

从数据库接收作为其他组件的道具的[[传递数据的正确方法是什么?我要以[[props to another component的形式发送customer.idcustomer.name

如何通过单击编辑地址功能中的按钮来发送这些数据?这是我的代码:

const CustomerAddress = (props) => { const history = useHistory() useEffect(() => { axios({ method: 'GET', url: 'http://localhost:8080/customer/showAddress/', headers: { Authorization: 'Bearer ' + localStorage.getItem('token'), }, }) .then((response) => { console.log(response.data) setData(response.data) setisLoaded(true) }) .catch((error) => { console.log(error) }) }, []) const [data, setData] = useState([]) const [isloaded, setisLoaded] = useState(false) const editAddress = () => { history.push('/UpdateAddress') } let customer = null if (isloaded) { customer = data.map((customer1) => ( <div> {customer1.id} {customer.name} <button className="btn btn-primary" onClick={() => editAddress(customer1.id)} > Delete </button> </div> )) } return <div> {customer} </div> }

reactjs function components
2个回答
0
投票
<Customer customerId={customerId} customerName={customerName} />

您可以从子组件的属性中访问值

如果该组件是现有组件的同级,则可以将值发送给父级,然后发送回所需的节点。

如果您有嵌套的组件结构,请使用Redux

如果您想在单击按钮时将数据发送给父级,

<Child getData={(data)=>{ // data is the value from the child // Statements to execute }} />

在孩子中,单击按钮时,您可以将数据传递给父母

this.props.getData(DATA_TO_SEND)
``


0
投票

onClick:

<button className="btn btn-primary" onClick={() => editAddress(customer1.id, customer1.name)} > Delete </button>

editAddress:

const editAddress = (customerId, customerName) => { history.push('/UpdateAddress', { customerId, customerName, }) }

const editAddress = (customerId, customerName) => {
  history.push({
    pathname: '/UpdateAddress',
    state: {
      customerId,
      customerName,
    },
  })
}

并且在UpdateAddress组件中,获取数据:

const customerId = this.props.history.location.state?.customerId
const customerName = this.props.history.location.state?.customerName

阅读全文:react-routerhistory

© www.soinside.com 2019 - 2024. All rights reserved.