Answer the question
In order to leave comments, you need to log in
How to trigger a re-render of a child component?
Hello! There is a Library class that renders two more components: Filter and LibraryContent. In LibraryContent, a certain address is passed through props (stored in the state of the parent component), by which it takes the data and displays it. Then, as a result of user actions,
a method is called in Library handleFilterChange
that changes the address in state. But LibraryContent is not re-rendered . I want it to re-render and take data at a new address.
export default class Library extends React.Component {
constructor(props) {
super(props);
this.state = {
url: '<адрес стороннего ресурса c какими-то параметрами>',
}
}
handleFilterChange = (name, event) => {
this.setState({
url: '<адрес с новыми параметрами>'
});
};
render() {
return (
<div className="library">
<Filter/>
<LibraryContent
url={this.state.url}
/>
</div>
)
}
}
export default class Library extends React.Component {
constructor(props){
super(props);
this.state = {
films: []
};
this.getData = this.getData.bind(this);
}
getData(){
console.log(this.props.url);
fetch(this.props.url)
.then(response => {
if (response.status !== 200) {
console.log('Код ошибки : ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(data => {
this.setState({films: data.results}, () => {
//console.log(this.state.films);
});
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
};
componentDidMount(){
this.getData();
}
render() {
const films = this.state.films.map(item =>
<div key={item.id} className={"film"}>
<FilmCard title={item.name}
imgUrl={this.props.imgUrlPrefix + item.poster_path}
overview={item.overview.substr(0, 150) + "..."}
movieUrl={"/library/" + item.id}
/>
</div>
);
return (
<div className="libraryContentWrapper">
{films}
</div>
)
}
}
Answer the question
In order to leave comments, you need to log in
Add to LibraryContent:
componentDidUpdate(prevProps) {
if (prevProps.url !== this.props.url) {
this.getData();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question