从数据库接收作为其他组件的道具的[[传递数据的正确方法是什么?我要以[[props to another component的形式发送customer.id
和customer.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>
}
<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)
``
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-router和history