[英]React/nextjs fetch data on a button click, but the button is in a different component
I have a function in the that fetches the weather data for current location when button is clicked.我有一个功能,可以在单击按钮时获取当前位置的天气数据。 I want to get this data from the Location component to the pages/index.tsx where I have another components that displays that data.
我想将此数据从 Location 组件获取到 pages/index.tsx ,其中我有另一个显示该数据的组件。
This is my component structure:这是我的组件结构:
App
--Layout
--Header
--Location (here i fetch the data on click)
--Home (state)
--Display 1
--SubDisplay 1
--Display 2
Do I have to pass the data through all the components to the index page?我是否必须将数据通过所有组件传递到索引页面? It would be:
这将是:
Is this the best way to handle this?这是处理这个问题的最好方法吗?
Due to React's nature regarding data flow, you can only pass props
down from parent component to its children, this is known as one-way data binding or unidirectional data flow.由于 React 的数据流特性,您只能将
props
从父组件传递给其子组件,这称为单向数据绑定或单向数据流。 Based on the structure of your components, to achieve what you want to do you would need to use Context
API or something like redux
to centralize your data in one place (or just lifting the states up).根据组件的结构,要实现您想要做的事情,您需要使用
Context
API 或类似redux
的东西将您的数据集中在一个地方(或者只是提升状态)。 However you can try this "workaround" so you don't need to modify your project's structure:但是,您可以尝试这种“解决方法”,这样您就不需要修改项目的结构:
Since your state is in the index/home page, you could define a function in this component that will receive as parameter the data fetched in Location
component and set the state with this data, of course you'd need to pass this function via props
to Layout
component so it can pass it to Header
and Header
to Location
(prop drilling), example:由于您的状态位于索引/主页中,因此您可以在此组件中定义一个函数,该函数将接收在
Location
组件中获取的数据作为参数并使用此数据设置状态,当然您需要通过props
传递此函数Layout
组件,以便它可以将其传递给Header
和Header
to Location
(道具钻孔),例如:
const Home = () => {
const [data, setData] = useState([]);
const handleData = (data) => {
setData(data);
}
return (
<Layout handleData={handleData}>
The rest of your components...
</Layout>
)
}
Then like I said, pass that function this way: Layout - Header - Location.然后就像我说的那样,以这种方式传递该函数:布局 - 标题 - 位置。
In Location
:在
Location
:
const Location = ({ handleData }) => {
const handleClick = () => {
// Fetch your data on click event and pass it as parameter to handleData function
handleData(fetchedData);
}
// The rest of your component...
}
Hope this helps you.希望这对您有所帮助。
Suggested solutions based on more complexity基于更复杂的建议解决方案
Lifting state up (Easier than other) sample code提升状态(比其他更容易)示例代码
const [weatherData,setWeatherData]=useState();
const shippingFunction = function(data) { setWeatherData(data);}
Location Component位置组件
Layout Component布局组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.