Вызов Fetch в React App.js с помощью Drilling - PullRequest
0 голосов
/ 31 октября 2019

Итак, я хотел бы вызвать fetch из функции (submitURL) в App.js. Если я создаю "componentDidMount ()" в App.js и вызываю там fetch, это работает, но не из submitURL. Я полагаю, что это потому, что submitURL вызывается с помощью пропил-бурения. Как бы я вызвал fetch из submitURL?


App.js

class App extends Component {
  state = {
      channelURL: '',
      videos: []
    }

  submitURL = (value) => {

    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => console.log(json))

    this.setState({
      channelURL: value
    });
  }

  render() {
    console.log(this.state)

    return (
      <div className="App">
        <h1> Title </h1>
        <Channel submitURL={this.submitURL} url={this.state.channelURL}/>
        <Videos videos={this.state.videos}/>
      </div>
    );
  }
}

export default App;

Channel.js

class Channel extends Component {
  state = {
    value: this.props.url
  }

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

  render() {
    return (
      <div>
        <h1> Enter Channel URL </h1>
        <form onSubmit={this.props.submitURL.bind(this, this.state.value)}>
          URL: <input type="text" name="url" value={this.state.value} onChange={this.handleChange}/>
          <input type="submit" value="Submit" />
        </form>
      </div>
    );
  }
}

export default Channel;

1 Ответ

1 голос
/ 31 октября 2019
submitURL = (value) => {

    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => this.setState({
      channelURL: json
    }))
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...