【问题标题】:React: How to properly update state of parent component after changing child componentReact:更改子组件后如何正确更新父组件的状态
【发布时间】:2021-04-22 21:56:15
【问题描述】:

我是 React 新手,想知道是否可以在这里获得一些建议。

我目前正在使用 Mapbox,并将地图坐标设置为曼哈顿以及有关城市的描述。我希望每次用户按下按钮时地图的描述和位置都会改变(例如,用户点击时地图会移动到布鲁克林)

本质上,我正在尝试构建这个:https://docs.mapbox.com/mapbox-gl-js/example/playback-locations/,但是社区只能通过按钮点击来滑动。我不确定如何将这个普通的 Javascript 和 html 转移到 React 中,所以我尝试尽可能地重新创建。

我的代码如下。我知道子组件是类组件,父组件是函数组件。

父组件

const locations = [
  {
    'id': '1',
    'title': 'Manhattan',
    'description': 'The capital of culture, finance, entertainment, and fashion. Need we say more?',
    'camera': {center: [-74.007, 40.7437], bearing: 25.3, zoom: 11.5}
  },
  {
    'id': '2',
    'title': 'Bronx',
    'description': "A fantastic zoo and botanical garden. Not to mention the birthplace of hip-hop!",
    'camera': {center: [-73.8709, 40.8255], bearing: 0, zoom: 12.21}
  },
  {
    'id': '3',
    'title': 'Brooklyn',
    'description': "This borough is experiencing a renaissance and continues to bring new surprises.",
    'camera': {center: [-73.9499, 40.626], bearing: -8.9, zoom: 11.68}
  },
  {
    'id': '4',
    'title': 'Queens',
    'description': "Experience one of the world's most diverse places!",
    'camera': {center: [-73.8432, 40.6923], bearing: 36, zoom: 11.37}
  },
  {
    'id': '5',
    'title': 'Staten Island',
    'description': 'A great place for family and friends with a stunning view, tons of parks, and a free ferry ride!',
    'camera': {center: [-74.1991, 40.5441], bearing: 28.4, zoom: 11.64}
  },
  {
    'title': 'Five Boroughs of New York',
    'description': 'New York City is made up of five boroughs: Bronx, Brooklyn, Manhattan, Queens and Staten Island. Each one has its own attractions-not to mention data!',
    'camera': {center: [-74.0315, 40.6989], zoom: 9.68, bearing: 0, pitch: 0}
  }
];


function Neighborhood() {
  const [count, setCount] = useState(0);
  const borough = <Boroughs data={locations[count]}/>
  const [map, setMap] = useState(borough); 

  function increase() {
    setCount(count+1);
    setMap(<Boroughs data={locations[count]}/>);
  }

  function decrease() {
    setCount(count-1);
    setMap(<Boroughs data={locations[count]}/>);
  }

  return (
    <div className="all-neighborhoods">
      <PageNavbar active="Listing" />
      <header className="App-header">
      </header>
      {count}
      <button onClick={decrease}>-</button>
      <button onClick={increase}>+</button>
      <div className="container-fluid">
        <div className="row d-flex flex-fill min-vh-100">
          {map}
        </div>
      </div>
    </div>
  );
}

export default Neighborhood; 

子组件

mapboxgl.workerClass = MapboxWorker;
mapboxgl.accessToken = '<hidden>';
 
export default class Boroughs extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      title: this.props.data.title,  
      description: this.props.data.description,
      lat: this.props.data.camera.center[0],
      long: this.props.data.camera.center[1],
      zoom: this.props.data.camera.zoom,
      bearing: this.props.data.camera.bearing
    }
    this.mapContainer = React.createRef();
  }

  componentDidMount() {
    const { lat, long, zoom, bearing } = this.state;
    const map = new mapboxgl.Map({
      container: this.mapContainer.current,
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [parseFloat(lat), parseFloat(long)],
      maxZoom: 16,
      minZoom: 9,
      zoom: parseFloat(zoom),
      bearing: parseFloat(bearing),
      pitch: 50 
    });
  }

  render() {
    const { title, description } = this.state;
    return (
      <div ref={this.mapContainer} className="map-container flex-grow-1">
        <div className="map-overlay-container">
          <div className="map-overlay">
            <h2 id="location-title">{title}</h2>
            <p id="location-description">{description}</p>
          </div>
        </div>
      </div> 
    );
  }
}

【问题讨论】:

    标签: javascript reactjs components mapbox mapbox-gl-js


    【解决方案1】:

    尝试阅读React Context API。任何包装在上下文提供者中的东西都会暴露给上下文的状态

    【讨论】:

      【解决方案2】:

      不建议子组件改变父组件的状态。不过有这个技巧,在父组件中添加一个更新状态的函数,将其作为道具传递给子组件,并在每次子组件发生更改时调用它。

      【讨论】:

        猜你喜欢
        • 2021-07-17
        • 1970-01-01
        • 2018-02-20
        • 1970-01-01
        • 2019-07-12
        • 1970-01-01
        • 1970-01-01
        • 2018-10-09
        • 1970-01-01
        相关资源
        最近更新 更多