首先,我创建了一个名为Roommate.Js
的类,其中我创建了一个函数,尝试以这种方式从URL获取数据(由id过滤的随机用户数据)。
roommateDetail() {
fetch(roommateDetail(this.props.id))
.then(response => {
if (!response.ok) {
throw Error("Failed connection to the API")
}
return response
})
.then(response => response.json())
.then(response => {
this.setState({
roommate: response
})
}, () => {
this.setState({
requestFailed: true
})
})
}
在其他名为Roomates(复数)的类中,随机显示了一个列表我在render方法中创建了这个代码:一个<a>
元素,它包含对roommateDetail
存在的调用在Roommate
类
render() {
return (
<div>
<ul>
{this.state.roommates.map(function(item) {
return <a key={item.id} onClick={Roommate.roommateDetail}><li key={item.id}>{item.name}</li></a>
})}
</ul>
</div>
);
}
最后,在主应用渲染功能中,我跳跃显示方法调用的结果。
render() {
return (
<div className="App">
<div className="App-center-side">
<div className="App-center-side-content">
<Roommate></Roommate>
</div>
</div>
</div>
);
}
当我点击<a>
元素时,我没有回复。也许我在某个地方犯了错误。
答案 0 :(得分:0)
我认为你可以像这样改变它
render() {
return (
<div>
<ul>
{this.state.roommates.map(function(item) {
return <a key={item.id} onClick={(e) => this.roommateDetail(item.id)}><li key={item.id}>{item.name}</li></a>
})}
</ul>
</div>
);
// add following method into your class
roommateDetail(id) {
fetch(roommateDetail(id))
.then(response => {
if (!response.ok) {
throw Error("Failed connection to the API")
}
return response
})
.then(response => response.json())
.then(response => {
this.setState({
roommate: response
})
}, () => {
this.setState({
requestFailed: true
})
})
}
答案 1 :(得分:0)
Roomate.js
class Roommate {
roommateDetail() {
fetch(roommateDetail(this.props.id))
.then(response => {
if (!response.ok) {
throw Error("Failed connection to the API")
}
return response
})
.then(response => response.json())
.then(response => {
this.setState({
roommate: response
})
}, () => {
this.setState({
requestFailed: true
})
})
}
render(){
return (<Roommates roommateDetail={this.roommateDetail.bind(this)}/>)
}
}
Roommates.js
class Roommates {
render(){
return(
<div>
<ul>
{this.state.roommates.map(function(item) {
return <a key={item.id} onClick=
{()=>this.props.roommateDetail}>
<li key={item.id}>{item.name}</li></a>
})}
</ul>
</div>
)
}
}
希望这可能会有所帮助:)