[英]How to send data from one react component to another react component?
Here I get some data from the 'Order' component and then I want to send this data to Navigate but all I get when using 'props.order_data' in 'Navigate' is undefined.在这里,我从“订单”组件中获取了一些数据,然后我想将此数据发送到 Navigate,但在“导航”中使用“props.order_data”时得到的所有数据都是未定义的。 How can I use this data in 'Navigate'?如何在“导航”中使用这些数据?
function App(){
function getData(some){
console.log(some);
return(<Navigate order_data= {some}/>);
}
return(
<div>
<Navigate />
<Service/>
<Order onAdd={getData}/>
<Review />
<Foot />
</div>
);
}
export default App;
What you are trying to do won't work as the return-value of the getData
function is passed to the Order
-component's onAdd
function.由于getData
function 的返回值被传递给Order
组件的onAdd
function,因此您尝试执行的操作将不起作用。
I would suggest that you create a state for the order_data
in your App-component and pass the state as a prop to the Navigate
-element that you are returning.我建议您为 App 组件中的order_data
创建一个 state 并将 state 作为道具传递给您要返回的Navigate
元素。 You will need to update the state as soon as you retrieve the data (eg in getData
function).检索数据后(例如在getData
函数中),您将需要更新 state。
React will take care of updating the component as soon as the state changes.一旦 state 发生变化,React 将负责更新组件。
See React documentation for more details: https://reactjs.org/docs/lifting-state-up.html有关更多详细信息,请参阅 React 文档: https://reactjs.org/docs/lifting-state-up.html
You need to use useState
hook to maintain a state.您需要使用useState
挂钩来维护 state。 Since you have your Navigate
and Order
component in the same Parent App
.由于您在同一个 Parent App
中有Navigate
和Order
组件。
Do like this这样做
import { useState } from "react";
function App(){
const [some, setSome] = useState(null); // Initial some value is null
function getData(data){
setSome(data); // This will update some state value
}
return(
<div>
<Navigate order_data={some}/>
<Service/>
<Order onAdd={getData}/>
<Review />
<Foot />
</div>
);
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.