如何从组件B更新组件A中的状态?

时间:2019-05-13 11:30:38

标签: javascript reactjs state jsx

下面的代码是主页中存在的一些代码,它们具有一个状态变量: cityCountry ,我试图将其解析为组件EuropeMap,以便可以进行更新EuropeMap组件中Home组件中的cityCountry。

import React, { Component } from "react";
import EuropeMap from "../components/EuropeMap";
//Styling
import "../css/index.css";
import "../css/grid.css";
import "../css/normalize.css";
//Components
import Footer from "../components/Footer";
import Search from "../components/SearchByCity";
import FetchClass from "../components/FetchClass";
import WeatherBox from "../components/WeatherBox";

class Home extends Component {
  constructor(props) {
    super(props);

    this.state = {
      weatherBoxId: "",
      weatherBox: false,
      city: this.props.city,
      cityCountry: [],
      weather: [
        {
          id: "",
          applicable_date: "",
          min_temp: "",
          max_temp: "",
          the_temp: "",
          wind_speed: "",
          weather_state_name: "",
          weather_state_abbr: "",
          wind_direction_compass: ""
        }
      ]
    };
  }



  render() {
    return (
      <div>
        <section className="section-map">
          <div className="row home-row">
            <div className="col span-2-of-3">
              <EuropeMap cityCountry={this.state.cityCountry} />
            </div>

            <div className="col span-1-of-3">
              //{this.showWeatherDetailed(this.state.weather)}
            </div>
            <div>
              <h2>Coming data</h2>
            </div>
          </div>
        </section>

下面的代码是EuropeMap中的方法,这些方法必须最终更新Home中的cityCountry状态,以触发Home render()方法,但是它似乎不起作用。

import React, { Component } from "react";
import "../css/index.css";
import FetchClass from './FetchClass';

class EuropeMap extends Component {
  state = {
    previousCountryStyle: "",
    currentCountryCode: "",
  };

  handleCountryClick = evt => {
    var countryCode = evt.target.id;
    this.findWoeidForCountry(countryCode);
    //FetchClass.fetchCitiesForClickedCountry({...this.state.countryObject});
    console.log(countryCode);

    if (this.state.previousCountryStyle === "") {
      this.setState({ currentCountryCode: countryCode });
      evt.target.style.fill = "#f96e10";
    } else {
      this.setState({ currentCountryCode: countryCode });
      this.setPreviousCountryToGrey(this.state.previousCountryStyle);
      evt.target.style.fill = "#f96e10";
    }
    this.setState({ previousCountryStyle: evt.target.style });
  };
  setPreviousCountryToGrey = st => {
    st.fill = "#c0c0c0";
  };

  findWoeidForCountry = async countryCode => {

    const woeid = require("woeid");
    console.log(woeid.getWoeid(countryCode));
    if (countryCode !== "svg2") {
      const woeid2 = woeid.getWoeid(countryCode);
      const result = await FetchClass.fetchCitiesForClickedCountry(woeid2.woeid);
      this.setState({cityCountry: result})
      console.log("BYER: ", result);
      console.log(woeid2.woeid, 'Europe Map Find Woeid Method');
    }
  };

有人可以告诉我,如何将状态变量解析到另一个组件,以便组件B中的我可以更新组件A中的状态?

谢谢:)

2 个答案:

答案 0 :(得分:0)

Home组件中创建一个函数,以更新cityCountry状态变量并将其作为prop转发给EuropeMap组件:

// in `Home`
updateCountry = (cityCountry) => this.setState({ cityCountry });

<EuropeMap updateCountry={this.updateCountry} { ... } />

// in `EuropeMap`
onSomethingHappend = () => {
    var data = somehowGetData();
    this.props.updateCountry(data);
}

答案 1 :(得分:0)

home组件中的create方法

updateCityCountry = val => this.setState({ cityCountry: val })

,而不是将组件呈现为

<EuropeMap cityCountry={this.state.cityCountry} />

渲染为

<EuropeMap cityCountry={this.state.cityCountry} updateCity={this.updateCityCountry} />

,您可以在“欧洲地图”组件中调用

this.props.updateCity(result)

这将在home组件中更新