【问题标题】:How can I update state in Component A from Component B?如何从组件 B 更新组件 A 中的状态?
【发布时间】:2019-05-13 11:30:38
【问题描述】:

以下代码是我们主页中存在的一些代码,其中有一个名为: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 中的状态?

谢谢:)

【问题讨论】:

    标签: javascript reactjs state jsx


    【解决方案1】:

    在 home 组件中创建方法

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

    而不是将组件渲染为

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

    渲染为

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

    在欧洲地图组件中可以调用

    this.props.updateCity(result)
    

    这将在 home 组件中更新

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-10
        • 2018-04-20
        • 1970-01-01
        • 1970-01-01
        • 2017-09-28
        • 1970-01-01
        • 2019-06-03
        • 2023-02-19
        相关资源
        最近更新 更多