我试图从子组件(TableOfContents)中设置父组件(App)的State,在这种情况下是一个无状态功能组件,这样一切都可以重新渲染和更新我的表。事件处理程序(changeUrl)被调用,据我所知状态改变但没有重新渲染,表没有更新!
class App extends React.Component {
root = 'https://fcctop100.herokuapp.com/api/fccusers/top/';
allTime = 'alltime';
recent = 'recent';
constructor(props) {
super(props);
this.state = { data: null,
url: this.root + this.allTime };
this.changeUrl = this.changeUrl.bind(this);
}
componentDidMount() {
return fetch(this.state.url)
.then(response => response.json())
.then(responseJson => {
this.setState({ data: responseJson });
});
}
changeUrl() {
this.setState({ url: this.root + this.recent });
}
render() {
return (
<div id="container">
<Head />
<TableOfContents handleClick={this.changeUrl} />
<Tables data={this.state.data}/>
</div>
);
}
}
const Head = (props) => {
return (
<div className="head">
freeCodeCamp Leaderboard
</div>
);
}
const TableOfContents = (props) => {
return (
<div className="tableOfContents">
<tr className="headers" >
<td>#</td>
<td id='special'>Camper Name</td>
<td onClick={props.handleClick} style={{cursor: 'pointer'}}>Points in last 30 days</td>
<td>All time points</td>
</tr>
</div>
);
}
const Tables = (props) => {
if (!props.data) return <p>Loading...</p>;
return (
<div className="tables">
{
props.data.map( (d, i) =>
<tr id={'table' + i}>
<td>{i + 1}</td>
<td><img src={d.img} /></td>
<td>{JSON.stringify(d.username).replace(/"/g, '')}</td>
<td>{JSON.stringify(d.recent)}</td>
<td>{JSON.stringify(d.alltime)}</td>
</tr>)
}
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
答案 0 :(得分:0)
如果要使用新数据填充表,还可以使用componentDidUpdate和componentDidMount来执行获取逻辑