简体   繁体   English

将返回值从一个组件传递到另一个组件

[英]Passing a return value from one component to another

I have two react components: Component1 renders a Map with MapboxGl.我有两个反应组件:Component1 使用 MapboxGl 呈现 Map。 Component2 renders a button that when clicked, makes an API call and fetches Geojson data and stores it into a variable. Component2 呈现一个按钮,当单击该按钮时,会进行 API 调用并获取 Geojson 数据并将其存储到变量中。

Problem: Component1 needs the Geojson data to draw a route on the map.问题:Component1 需要 Geojson 数据在 map 上绘制路线。 How can I pass the the data from component2 to component1?如何将数据从组件 2 传递到组件 1? I tried with exporting the variable from component2 and importing it in component1, but it doesn't work.我尝试从component2中导出变量并将其导入component1,但它不起作用。

Any help would be much appreciated.任何帮助将非常感激。

In this case, I recommend using either React Context or Redux .在这种情况下,我建议使用React ContextRedux

Here's the gist with context (it's a bit simpler imho than Redux).这是带有上下文的要点(恕我直言,它比 Redux 简单一些)。 The example is based off this article .该示例基于这篇文章

import React, { createContext, useContext, useState } from 'react'

const GeoJSONContext = createContext({})  // this will be the geojson data.

const GeoJSONProvider = GeoJSONContext.Provider

const ButtonContainer = (props) => {
  const { setGeoJSON } = useContext(GeoJSONContext)

  return <Button onClick={() => setGeoJSON(await fetchGeoJSON())}> 
             Get Data 
         </Button>
}

const MapContainer = (props) => {
  const { geoJSON } = useContext(GeoJSONContext)

  return <Map data={geoJSON} />
}

const App = (props) => {
   const [geoJSON, setGeoJSON] = useState([])

   return (<GeoJSONProvider value={{ geoJSON, setGeoJSON }}>
             <MapContainer />
             <ButtonContainer />
           </GeoJSONProvider>)
}

You can pass a function to the Button component as prop and call it when data is received.您可以将 function 作为 prop 传递给Button组件,并在收到数据时调用它。 This means the container component hosting the map and the button component needs to keep state for the returned data.这意味着托管 map 的容器组件和按钮组件需要为返回的数据保留 state。 The state is then passed as property to the Map component然后将 state 作为属性传递给Map组件

If the 2 components that you are having are independent to each other then what you probably need is a state container such as react-redux .如果您拥有的 2 个组件彼此独立,那么您可能需要一个 state 容器,例如react-redux Wrap the 2 components in a new component and move all the data that needs to be shared in the store.将这 2 个组件包装在一个新组件中,并将需要在存储中共享的所有数据移动。 Otherwise go by Wakeel's answer - props .否则,Wakeel 的答案是 go - props

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM