簡體   English   中英

React:更改子組件后如何正確更新父組件的 state

[英]React: How to properly update state of parent component after changing child component

我是 React 的新手,想知道是否可以在這里得到一些建議。

我目前正在使用 Mapbox,並將 map 坐標設置為曼哈頓以及有關城市的描述。 我希望每次用戶按下按鈕時 map 的描述和位置都會改變(例如,用戶點擊后 map 將移動到布魯克林)

從本質上講,我正在嘗試構建這個: https://docs.mapbox.com/mapbox-gl-js/example/playback-locations/ ,但社區只滑動到按鈕點擊。 我不確定如何將這個普通的 Javascript 和 html 移動到 React 中,所以我嘗試盡可能地重新創建。

我的代碼如下。 我知道子組件是 class 組件,父組件是 function 組件。

父組件

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> 
    );
  }
}

嘗試閱讀React 上下文 API 包含在上下文提供程序中的任何內容都將暴露給上下文的狀態

不建議孩子更改父組件的state。 但是有這個 hack,在更新 state 的父級中添加一個 function,將其作為道具傳遞給子級,並在每次子組件發生更改時調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM