【发布时间】:2018-06-05 20:17:59
【问题描述】:
我有一个简单的 React 应用程序,它由 3 个组件组成: 1. 包含链接的侧边栏 2. 包含表中数据的ItemList 3. 包装它们的包装器(我从这里的一些帖子中了解到它有时很有用,因为我想在单击侧边栏上的不同链接后更新 ItemsList 组件)。
我现在的工作:
在主 Wrapper 组件中:
render() {
return (
<div>
<SideMenu handleClick={this.handleClick} />
<ItemsList url={this.state.currentUrl} />
</div>
);
}
应用程序一启动,在 ItemsList 组件中使用 componentDidMount(),它会在那里获取数据并显示它。效果很好。
问题是,当我单击 sideMenu 组件中的链接时,我正在更改主包装器状态下的 currentUrl,因此它将被新的 url 重新渲染:
handleClick() {
this.setState({ currentUrl: 'here I put the new address to fetch from'});
}
但获取的是位于前一个 url 中的数据,而不是我刚刚将其更改为的数据。 基本上,在我调试并检查更改后的状态之后,currentUrl 保持之前的状态,然后它使用之前的 url 重新渲染 ItemList。
我的问题是,如何使用这个 handleClick() 方法更改 itemList 的内容?希望我能得到一些见解。非常感谢,非常感谢您的帮助。
主包装代码:
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
currentUrl: 'current url to fetch from...',
data: []
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ currentUrl: 'the new url ' });
}
render() {
return (
<div>
<SideMenu handleClick={this.handleClick} />
<ItemsList url={this.state.currentUrl} />
</div>
);
}
}
我的项目列表组件:
class ItemsList extends Component {
constructor(props) {
super(props);
this.state = { url: props.url, data: [] };
}
componentDidMount() {
return fetch(this.state.url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({ data: responseJson.data });
})
}
render() {
return (
displaying the table html tags..
}
</div>
)
}
}
【问题讨论】: