如何在 React JS 中将参数传递给 componentDidMount 方法

我想通过 App.js 中的按钮获取用户的输入,从站点 API 获取一些信息(数据 id),然后使用获取的信息(id)通过将 id 发送到来向用户显示所需的信息Population.js 但它无法正常工作。我认为 componentDidUpdate 可能需要一些参数,因为我必须发送的获取请求需要用户输入才能工作。此外,我认为我的代码甚至在用户按下按钮之前就正在获取信息,因为控制台没有显示正确的信息我需要的 id(它显示 4-5 个值,但全部都不正确)。如果我对值进行硬编码,它就可以正常工作。基本上,我想通过按钮获取输入,使用该输入来获取某些内容,然后使用获取的内容来获取其他内容,然后显示获取的信息。请帮助我。我是 React 的初学者。这是APP.js

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

        });

      }



森栏
浏览 147回答 2
2回答

慕斯709654

您的要求不同,您不必在这里使用 componentDidMount,因为您将在用户按下搜索按钮后进行服务调用。我已经修改了您的代码以在按下按钮时工作,并将代码传递给填充组件,该组件在 componentDidMount 和 componentDidUpdate 上调用 api,因为代码将来可能会更新class App extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = { name: "", info: {}, formSubmit: false, code: "" };&nbsp; &nbsp; this.handleInput = this.handleInput.bind(this);&nbsp; &nbsp; this.handleFormSubmit = this.handleFormSubmit.bind(this);&nbsp; }&nbsp; handleInput(event) {&nbsp; &nbsp; console.log(event.target.value);&nbsp; &nbsp; &nbsp;this.setState({ name: event.target.value, formSubmit: false });&nbsp; }&nbsp; handleFormSubmit(event) {&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; fetch(&nbsp; &nbsp; &nbsp; `https://wft-geo-db.p.rapidapi.com/v1/geo/cities?namePrefix=${this.state.name}`,&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; method: "GET",&nbsp; &nbsp; &nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "x-rapidapi-key":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "x-rapidapi-host": "wft-geo-db.p.rapidapi.com"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; .then((response) => response.json())&nbsp; &nbsp; &nbsp; .then((data) => {&nbsp; &nbsp; &nbsp; &nbsp; const newInfo = data.data;&nbsp; &nbsp; &nbsp; &nbsp; const newName = newInfo[0].wikiDataId;&nbsp; &nbsp; &nbsp; &nbsp; const newState = Object.assign({}, this.state, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; info: newInfo[0],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; code: newName,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; formSubmit: true&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; this.setState(newState);&nbsp; &nbsp; &nbsp; &nbsp; console.log("The sent code " + this.state.name);&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch((err) => {&nbsp; &nbsp; &nbsp; &nbsp; console.error(err);&nbsp; &nbsp; &nbsp; });&nbsp; }&nbsp; componentDidUpdate() {&nbsp; &nbsp; //the value property needs to be fetched from user&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; &nbsp; <h1>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Enter the name of the city: <br />&nbsp; &nbsp; &nbsp; &nbsp; </h1>&nbsp; &nbsp; &nbsp; &nbsp; <form>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Enter the city name to get the population:{" "}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.name}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChange={this.handleInput}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onClick={this.handleFormSubmit}>Enter</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </label>&nbsp; &nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; &nbsp; &nbsp; {this.state.formSubmit && <Population name={this.state.code} />}&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}人口组成就像class Population extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; info: {},&nbsp; &nbsp; &nbsp; population: 0&nbsp; &nbsp; };&nbsp; &nbsp; this.getPopulation = this.getPopulation.bind(this);&nbsp; }&nbsp; getPopulation(name) {&nbsp; &nbsp; fetch(`https://wft-geo-db.p.rapidapi.com/v1/geo/cities/${name}`, {&nbsp; &nbsp; &nbsp; method: "GET",&nbsp; &nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; &nbsp; "x-rapidapi-key": "",&nbsp; &nbsp; &nbsp; &nbsp; "x-rapidapi-host": "wft-geo-db.p.rapidapi.com"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .then((response) => response.json())&nbsp; &nbsp; &nbsp; .then((data) => {&nbsp; &nbsp; &nbsp; &nbsp; const newInfo = data.data;&nbsp; &nbsp; &nbsp; &nbsp; const newPopulation = newInfo.population;&nbsp; &nbsp; &nbsp; &nbsp; const newState = Object.assign({}, this.state, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; info: newInfo,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; population: newPopulation&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; this.setState(newState);&nbsp; &nbsp; &nbsp; &nbsp; console.log(this.state.info);&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch((error) => {&nbsp; &nbsp; &nbsp; &nbsp; console.error(error);&nbsp; &nbsp; &nbsp; });&nbsp; }&nbsp; componentDidMount() {&nbsp; &nbsp; if (this.props.name) {&nbsp; &nbsp; &nbsp; this.getPopulation(this.props.name);&nbsp; &nbsp; &nbsp; console.log("The name " + this.props.name);&nbsp; &nbsp; }&nbsp; }&nbsp; componentDidUpdate() {&nbsp; &nbsp; if (this.props.name) {&nbsp; &nbsp; &nbsp; this.getPopulation(this.props.name);&nbsp; &nbsp; &nbsp; console.log("The name " + this.props.name);&nbsp; &nbsp; }&nbsp; }&nbsp; render() {&nbsp; &nbsp; return <div className="App">The population is {this.state.population}</div>;&nbsp; }}

有只小跳蛙

一旦组件安装,就会调用 componentDidMount 函数,因此一旦组件安装,它就会执行获取操作。如果您希望在单击按钮时发生获取操作,则必须将代码放置在自定义函数中并在单击按钮时调用它。我认为您无法将任何道具传递给已安装的组件,因为您无法控制何时调用它。componentDidUpdate可能对您有用
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript