亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 React JS 中將參數傳遞給 componentDidMount 方法

如何在 React JS 中將參數傳遞給 componentDidMount 方法

森欄 2023-07-20 14:58:02
我想通過 App.js 中的按鈕獲取用戶的輸入,從站點 API 獲取一些信息(數據 id),然后使用獲取的信息(id)通過將 id 發送到來向用戶顯示所需的信息Population.js 但它無法正常工作。我認為 componentDidUpdate 可能需要一些參數,因為我必須發送的獲取請求需要用戶輸入才能工作。此外,我認為我的代碼甚至在用戶按下按鈕之前就正在獲取信息,因為控制臺沒有顯示正確的信息我需要的 id(它顯示 4-5 個值,但全部都不正確)。如果我對值進行硬編碼,它就可以正常工作?;旧?,我想通過按鈕獲取輸入,使用該輸入來獲取某些內容,然后使用獲取的內容來獲取其他內容,然后顯示獲取的信息。請幫助我。我是 React 的初學者。這是APP.jsimport React from 'react';import './App.css';import Population from './Population.js';class App extends React.Component {    constructor(props) {        super(props);        this.state = { name: "" ,info : {},formSubmit: false};        this.handleInput = this.handleInput.bind(this);        this.handleFormSubmit = this.handleFormSubmit.bind(this);    }             handleInput (event) {        console.log(event.target.value);      }          handleFormSubmit (event) {        event.preventDefault();        console.log("the value " + event.target.value);        this.setState({formSubmit: true,name : event.target.value});      }              componentDidMount(){//the value property needs to be fetched from user         fetch(`https://wft-geo-db.p.rapidapi.com/v1/geo/cities?namePrefix=${value}`, {            "method": "GET",            "headers": {                "x-rapidapi-key": "c4ab967692mshc65dd5c6e10a987p1790bejsn81ea7b831444",                "x-rapidapi-host": "wft-geo-db.p.rapidapi.com"            }        })        .then(response => response.json())        .then(data => {            const newInfo = data.data;            const newName = newInfo[0].wikiDataId;            const newState = Object.assign({},this.state,{                info : newInfo,                name : newName            });            this.setState(newState);            console.log("The sent code " + this.state.name);        })        .catch(err => {            console.error(err);        });      }
查看完整描述

2 回答

?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

您的要求不同,您不必在這里使用 componentDidMount,因為您將在用戶按下搜索按鈕后進行服務調用。


我已經修改了您的代碼以在按下按鈕時工作,并將代碼傳遞給填充組件,該組件在 componentDidMount 和 componentDidUpdate 上調用 api,因為代碼將來可能會更新


class App extends React.Component {

  constructor(props) {

    super(props);

    this.state = { name: "", info: {}, formSubmit: false, code: "" };

    this.handleInput = this.handleInput.bind(this);

    this.handleFormSubmit = this.handleFormSubmit.bind(this);

  }


  handleInput(event) {

    console.log(event.target.value);

     this.setState({ name: event.target.value, formSubmit: false });

  }


  handleFormSubmit(event) {

    event.preventDefault();


    fetch(

      `https://wft-geo-db.p.rapidapi.com/v1/geo/cities?namePrefix=${this.state.name}`,

      {

        method: "GET",

        headers: {

          "x-rapidapi-key":

            "",

          "x-rapidapi-host": "wft-geo-db.p.rapidapi.com"

        }

      }

    )

      .then((response) => response.json())

      .then((data) => {

        const newInfo = data.data;

        const newName = newInfo[0].wikiDataId;

        const newState = Object.assign({}, this.state, {

          info: newInfo[0],

          code: newName,

          formSubmit: true

        });

        this.setState(newState);

        console.log("The sent code " + this.state.name);

      })

      .catch((err) => {

        console.error(err);

      });

  }


  componentDidUpdate() {

    //the value property needs to be fetched from user

  }


  render() {

    return (

      <div className="App">

        <h1>

          Enter the name of the city: <br />

        </h1>

        <form>

          <label>

            Enter the city name to get the population:{" "}

            <input

              type="text"

              value={this.state.name}

              onChange={this.handleInput}

            />

            <button onClick={this.handleFormSubmit}>Enter</button>

          </label>

        </form>

        {this.state.formSubmit && <Population name={this.state.code} />}

      </div>

    );

  }

}

人口組成就像


class Population extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      info: {},

      population: 0

    };

    this.getPopulation = this.getPopulation.bind(this);

  }


  getPopulation(name) {

    fetch(`https://wft-geo-db.p.rapidapi.com/v1/geo/cities/${name}`, {

      method: "GET",

      headers: {

        "x-rapidapi-key": "",

        "x-rapidapi-host": "wft-geo-db.p.rapidapi.com"

      }

    })

      .then((response) => response.json())

      .then((data) => {

        const newInfo = data.data;

        const newPopulation = newInfo.population;

        const newState = Object.assign({}, this.state, {

          info: newInfo,

          population: newPopulation

        });

        this.setState(newState);

        console.log(this.state.info);

      })

      .catch((error) => {

        console.error(error);

      });

  }


  componentDidMount() {

    if (this.props.name) {

      this.getPopulation(this.props.name);

      console.log("The name " + this.props.name);

    }

  }


  componentDidUpdate() {

    if (this.props.name) {

      this.getPopulation(this.props.name);

      console.log("The name " + this.props.name);

    }

  }


  render() {

    return <div className="App">The population is {this.state.population}</div>;

  }

}


查看完整回答
反對 回復 2023-07-20
?
有只小跳蛙

TA貢獻1824條經驗 獲得超8個贊

一旦組件安裝,就會調用 componentDidMount 函數,因此一旦組件安裝,它就會執行獲取操作。如果您希望在單擊按鈕時發生獲取操作,則必須將代碼放置在自定義函數中并在單擊按鈕時調用它。我認為您無法將任何道具傳遞給已安裝的組件,因為您無法控制何時調用它。componentDidUpdate可能對您有用



查看完整回答
反對 回復 2023-07-20
  • 2 回答
  • 0 關注
  • 193 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號