onChange事件从粘贴(ctrl + v)接收到数据后重新启动反应发起组件

问题描述 投票:0回答:1

我正在尝试将URL粘贴到输入字段中后发起API请求,然后在页面上显示结果。

根据文档和SOF上的this链接,setState是启动重新渲染的方式,我知道,看来我自己做得正确,但是有些问题,只有在执行此操作时,我才能获得url状态再次onChange上,React似乎没有在任何可用生命周期事件中的任何地方向我显示我粘贴的数据。

使用create-react-app:

import React from "react";
import ReactDOM from "react-dom";

const UserInput = props => {
  return (
    <div>
      <label>Enter URL:</label>
      <input onChange={props.handleChange} type="text" value={props.value} />
    </div>
  );
};

class Fetch extends React.Component {
  constructor() {
    super();
    this.state = {
      url: null,
      userData: null,
      fetching: false,
      error: null
    };
  }

  componentDidUpdate() {
    this.fetchData();
  }

  fetchData() {
    fetch(this.state.url)
      .then(result => result.json())
      .then(json => this.setState({ userData: json }))
      .error(error => console.log(error));
  }

  render() {
    return this.props.render();
  }
}

const UserProfile = ({ name, gender }) => {
  return (
    <div>
      Hey {name}, you are {gender}!
    </div>
  );
};

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      url: null
    };
  }

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

  render() {
    return (
      <div>
        <UserInput
          value={this.state.url}
          handleChange={this.handleChange.bind(this)}
        />
        <Fetch url={this.state.url} render={data => <UserProfile />} />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

如果将任何URL粘贴到字段中,则不会使其处于状态,因此在触发fetchData时将其处于状态

this.state.url

实际上仍然为空。

谢谢

javascript reactjs
1个回答
0
投票

[您的提取组件和App组件正在使用url状态的两个单独副本,这会导致问题,您必须使用作为道具传递给url组件的Fetch

class Fetch extends React.Component {
  constructor() {
    super();
    this.state = {
      // url: null, remove this
      userData: null,
      fetching: false,
      error: null
    };
  }

  componentDidUpdate() {
    this.fetchData();
  }

  fetchData() {
    fetch(this.props.url) // update here
      .then(result => result.json())
      .then(json => this.setState({ userData: json }))
      .error(error => console.log(error));
  }

  render() {
    return this.props.render();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.