通过Prop Drilling在React App.js中调用Fetch

时间:2019-10-31 03:32:07

标签: reactjs http fetch

所以我想从App.js中的函数(submitURL)调用fetch。如果我在App.js中创建“ componentDidMount()”并在其中调用fetch,则可以正常运行,但不能从SubmitURL中获取。我相信这是因为SubmitURL是通过prop钻孔调用的。我怎么称呼从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 个答案:

答案 0 :(得分:1)

submitURL = (value) => {

    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => this.setState({
      channelURL: json
    }))
  }