应将此值保留在父级组件中
state
把它作为道具传给孩子。
当您的
onClick
被解雇了你应该更新父母
状态
如此更新
props
将传递给孩子。
代码如下:
锦标赛js公司
import React, { Component } from "react";
import Template from './template';
const API = 'http://localhost:8080/api/tournaments';
class Tournaments extends Component {
constructor() {
super();
this.state = {
data: [],
targetId: null,
}
}
componentDidMount() {
fetch(API)
.then((Response) => Response.json())
.then((findresponse) => {
console.log(findresponse)
this.setState({
data:findresponse,
})
})
}
reply_click = id => {
return () => {
this.setState({ targetId: id })
}
}
render() {
return(
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="jumbotron text-center">
{
this.state.data.map((dynamicData, key) =>
<div>
<a href={"/#/template"} onClick={this.reply_click(dynamicData.id)}>{dynamicData.name}</a>
<a href={"/#/addTeams"}><button type="button" class="btn-lisa">Edit</button></a>
<Template name={dynamicData.id} targetId={this.state.targetId}></Template>
</div>
)
}
</div>
</div>
</div>
</div>
)
}
}
export default Tournaments;
样板js公司
import React, { Component } from "react";
import Parser from 'html-react-parser';
import Tournaments from "./Tournaments";
import './template.css';
import './index.css';
const tournyAPI = 'http://localhost:8080/api/tournaments';
const teamAPI = 'http://localhost:8080/api/teams'
class template extends Component {
constructor() {
super();
this.state = {
data: [],
}
}
componentDidMount() {
fetch(tournyAPI)
.then((Response) => Response.json())
.then((findresponse) => {
this.setState({
tournydata: findresponse.filter(res => res.id === this.props.targetId),
})
})
但是使用
componentDidUpdate
而不是
componentDidMount
如果您想随时更新
样板
每次更换后的组件
targetId
。
像这样:
样板js公司
componentDidUpdate(prevProps) {
if (prevProps.targetId !== this.props.targetId) {
fetch(tournyAPI)
.then((Response) => Response.json())
.then((findresponse) => {
this.setState({
tournydata:findresponse.filter(res => res.id === this.props.targetId),
})
})
}
}
如果需要在第一次渲染时立即执行,只需添加检查
targetId
不是
null
在您的
Tournament
组成部分
类似这样:
锦标赛js公司
render() {
...
{this.state.targetId ? <Template name={dynamicData.id} targetId={this.state.targetId}></Template> : null }
...
}