React 启动组件在 onChange 事件从粘贴 (ctrl+v) 接收数据后重新渲染



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

根据文档和 SOF 上的此链接,setState 是启动重新渲染的方式,我知道,似乎我自己以正确的方式做了,但是有些东西不对劲,只有当我再次执行 onChange 时,我才会获得 url 状态,React 似乎没有在任何可用生命周期事件中的任何位置向我显示我粘贴的数据。

使用创建-反应-应用:

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

实际上仍然为空。

谢谢

您的 Fetch 组件和 App 组件正在使用导致问题的url状态的两个单独副本,您必须改用作为 prop 传递给Fetch组件的url

class Fetch extends React.Component {
constructor(props) {
super(props);
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(userData); // the render prop is a function in your case that expects data
}
}

也更新以下行,以便用户配置文件获取从 API 获取的数据。我不确定钥匙

<Fetch url={this.state.url} render={data => <UserProfile name={data.name} gender={data.gender}/>} />