【发布时间】:2025-12-19 21:50:18
【问题描述】:
我有一个组件,用户单击按钮转到另一个页面 (localhost:3020 --> localhost:3020/python)。我想使用在App.js 的输入框中输入的 url 向返回 JSON 对象的 Python 脚本发出 ajax 请求,然后将其存储到 posts 数组中。然后我想在单击按钮时将post 数组中的值传递给PythonComponent.js。当我输入 URL 并单击链接时,我的 console.log 语句会显示在控制台中,但我没有看到来自 posts 的任何文本呈现。
如果我在App.js 的状态中创建一个虚拟变量,使用输入框中的文本更新状态,输入框文本将呈现在localhost:3020/python 上。当我在进行 ajax 调用后尝试返回 posts 时,它不起作用。
我的问题是如何将posts 从App.js 传递到PythonComponent.js?
App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
posts=[]
};
this.handleClick = this.handleClick.bind(this);
}
handleClick () {
const urlBox = document.getElementById("box").value;
this.setState({
sendText: urlBox,
})
$.ajax({
type: "GET",
data: { arg1: urlBox} ,
url: "http://127.0.0.1:5000/hello/",
}).done(function(res) {
this.setState({posts:res
});
console.log(res.title, res.text)
}.bind(this));
}
render() {
return (
<div className="App">
<div>
<p className = "input-title"> Enter a URL</p>
<input placeholder = "placeholder text" id="box" ref="textBox" type="text"/>
<button onClick={this.handleClick}>
<Link to={{pathname:"/python", message: this.state.posts.title}}> cant use button have to use link text </Link>
</button>
</div>
</div>
);
}
}
export default App;
index.js
<BrowserRouter>
<Switch>
<Route path='/python' component={PythonComponent} />
<Route path='/' component={App} />
</Switch>
</BrowserRouter>
PythonComponent.js
class PythonComponent extends Component {
render() {
return (
<div>
<Link to={{pathname:"/"}}> home </Link>
<h1> HI </h1>
{this.props.location.message}
</div>
);
}
}
export default PythonComponent;
【问题讨论】:
标签: javascript reactjs components state