Как вставить входное значение в параметр для вызова API - PullRequest
0 голосов
/ 19 июня 2020

У меня есть компонент Header.js, который принимает ввод пользователя и обновляет его состояние. Я хочу передать (поддержать?) Этот элемент в родительский компонент App.js, где он будет помещен в качестве параметра, и данные будут регистрироваться в консоли относительно ввода пользователя. Я не знаю, как передать состояние и реализовать его в параметре API.

class Header extends Component {
  constructor() {
    super();
    this.state = {
      query: '',
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    // form's input value
    let userSearch = this.state.query;
  }

  handleChange = (e) => {
    this.setState({
      query: e.target.value
    });
  }

  render() {
    return (
      <header>
        <form onSubmit={this.handleSubmit}>
          <input 
            onChange={this.handleChange} 
            type="text" 
            placeholder="Search"
          />
          <label className="sr-only" htmlFor="search">Search News</label>
        </form>
      </header>
    )
  }
}

export default Header


import Header from './Components/Header'
import axios from 'axios';


class App extends Component {
  constructor() {
    super();
    this.state = {
      articles: [],
    }
  }

  componentDidMount() {
    axios({
      // I want this.state.query in header.js to be {parameter}
      url: 'http://newsapi.org/v2/everything?q={parameter}&sortBy=popularity&apiKey=where-the-key-goes',
      method: 'GET',
      responseType: 'JSON',
    }).then((response => {
      let articles = response.data.articles;
      this.setState({
        articles,
        isLoading: false,
      })

      console.log(articles);
    }))
  }

  render() {
    return (
      <>
        <Header />
      </>
    )
  }
}

export default App

Ответы [ 3 ]

1 голос
/ 19 июня 2020

Вы можете создать функцию обратного вызова в компоненте App и передать в Header как опору:

class App extends Component {

  ...

  handleSearch = (value) => {
    axios({
      url: `http://newsapi.org/v2/everything?q=${value}&sortBy=popularity&apiKey=where-the-key-goes`,
      method: "GET",
      responseType: "JSON",
    }).then((response) => { ... });
  };

  render() {
    return (
      <>
        <Header handleSearch={this.handleSearch} />
      </>
    );
  }
}

Затем использовать ее в функции Header s handleSubmit:

handleSubmit = (e) => {
  e.preventDefault();
  // form's input value
  let userSearch = this.state.query;
  this.props.handleSearch(userSearch);
};
0 голосов
/ 19 июня 2020

Вы должны добавить реквизит из приложения. js. Также вам не нужно вызывать api для componentDidMount, потому что вы еще хотите получить запрос. Попробуйте это:

class Header extends Component {
    static defaultProps = {
        onUpdate: () => {},
        onSubmission: () => {}
    }

    constructor() {
        super();
        this.state = {
            query: '',
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        // form's input value
        let userSearch = this.state.query;
        this.props.onSubmission(this.state.query); //Send submission to parent
    }

    handleChange = (e) => {
        this.setState({
            query: e.target.value
        }, () => {
            this.props.onUpdate(this.state.query); //Send change to parent
        });
    }

    render() {
        return (
            <header>
                <form onSubmit={this.handleSubmit.bind(this)}>
                    <input
                        onChange={this.handleChange.bind(this)}
                        type="text"
                        placeholder="Search"
                    />
                    <label className="sr-only" htmlFor="search">Search News</label>
                </form>
            </header>
        )
    }
}

export default Header


import Header from './Components/Header'
import axios from 'axios';


class App extends Component {
    constructor() {
        super();
        this.state = {
            articles: [],
            query: ""
        }
    }

    componentDidMount() {

    }

    request(query){
        axios({
            // I want this.state.query in header.js to be {parameter}
            //NOTE: Query could also be this.state.query since we're updating it on change
            url: 'http://newsapi.org/v2/everything?q={parameter}&sortBy=popularity&apiKey=where-the-key-goes',
            method: 'GET',
            responseType: 'JSON',
        }).then((response => {
            let articles = response.data.articles;
            this.setState({
                articles,
                isLoading: false,
            })

            console.log(articles);
        }))
    }

    render() {
        return (
            <>
                <Header onUpdate={query => this.setState({query: query})} onSubmission={this.request.bind(this)} />
            </>
        )
    }
}

export default App
0 голосов
/ 19 июня 2020
class Header extends Component<Props> { // add Props
    ...
    handleSubmit = (e) => {
        e.preventDefault();
        // form's input value
        let userSearch = this.state.query;
        this.props.onValueSet(userSearch); // callback
    }
    ...
}

class App extends Component {
    ...
    // add callback
    _setValueHandle = (value) => {
        console.log(value);
        this.setState({parameter: value}); // do something u want
    };

    render() {
        return (
            <>
                {/* set callback */}
            <Header onValueSet={this._setValueHandle} />
        </>
    )}
    ...
}

как насчет этого?

...