【发布时间】:2019-04-18 18:55:53
【问题描述】:
这里有点混乱。我有一个 App 组件,它执行获取 API 请求以使用属性卡填充页面。我的属性组件呈现一个侧边栏来过滤这些卡片。该侧边栏中的链接进行了正确的 API 调用,并获得了正确的响应——但该响应不会导致 App 组件使用更少的属性重新渲染。
我认为我需要在 App 中使用 ComponentDidUpdate 方法,或者在 Properties 中扩展 ComponentDidUpdate 方法,但我不确定是哪个。有人能指出我正确的方向吗?
应用组件
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
properties: [],
};
}
componentDidMount() {
Axios.get('http://localhost:3000/api/v1/PropertyListing')
.then((response) => {
this.setState({
properties: response.data,
});
});
}
render() {
return (
<div className="navigation">
<NavBar />
<Switch>
<Route exact path="/" component={Properties} />
<Route exact path="/add-property" component={AddProperty} />
</Switch>
<PropertyCards
properties={this.state.properties}
/>
</div>
);
}
}
属性组件
class Properties extends React.Component {
constructor(props) {
super(props);
this.state = {
properties: [],
};
}
componentDidUpdate(prevProps) {
const { search } = this.props.location;
if (prevProps.location.search !== search) {
Axios.get(`http://localhost:3000/api/v1/PropertyListing${search}`)
.then(({ data: properties }) => this.setState({ properties }))
.catch(err => console.error(err));
}
}
render() {
return (
<div className="sidebar">
<h4>Filter by city</h4>
<div className="filters">
<Link className="filter" to={'/?query={"city":"Manchester"}'}>Manchester</Link>
<Link className="filter" to={'/?query={"city":"Leeds"}'}>Leeds</Link>
<Link className="filter" to={'/?query={"city":"Sheffield"}'}>Sheffield</Link>
<Link className="filter" to={'/?query={"city":"Liverpool"}'}>Liverpool</Link>
</div>
</div>
);
}
}
【问题讨论】:
标签: reactjs components rendering