Javascript 使用React Router单击新组件时,嵌入的子组件不会发生更改
今天早些时候,我第一次开始使用React Router,我想在文章索引中嵌入一篇文章的视图。这是可行的,唯一的问题是,当我想更改文章时,url会更改,我也会从新文章中获得信息,但视觉上没有任何变化 以下是来自父组件和子组件的代码: articles.js article.js 我忘了什么吗 提前感谢更改url参数时,文章组件不会重新安装,因此不会调用componentDidMount方法。您应该使用componentWillReceiveProps方法检查参数是否已更改Javascript 使用React Router单击新组件时,嵌入的子组件不会发生更改,javascript,reactjs,react-router,Javascript,Reactjs,React Router,今天早些时候,我第一次开始使用React Router,我想在文章索引中嵌入一篇文章的视图。这是可行的,唯一的问题是,当我想更改文章时,url会更改,我也会从新文章中获得信息,但视觉上没有任何变化 以下是来自父组件和子组件的代码: articles.js article.js 我忘了什么吗 提前感谢更改url参数时,文章组件不会重新安装,因此不会调用componentDidMount方法。您应该使用componentWillReceiveProps方法检查参数是否已更改 componentD
componentDidMount() {
this.loadArticle(this.props.match.params.slug);
}
componentWillReceiveProps(newProps) {
if (this.props.match.params.slug !== newProps.match.params.slug) {
this.loadArticle(newProps.match.params.slug);
}
}
浏览器控制台中出现错误?绝对没有。非常感谢,我在修改代码时遇到了麻烦,因为我忘了更改componentDidMount函数,但现在一切都正常工作:D
import React from 'react';
import utils from '../lib/functionsLibrary';
export default class Article extends React.Component {
constructor(props) {
super(props);
this.state = {article: null};
}
componentDidMount() {
let self = this;
// I retrieve the list of articles ever saved, and filter them
// with the slug I passed as parameter / url
utils.loader(window.location.origin + '/all_articles.json', function (articles) {
self.setState({
article: articles.find(a => a.slug === self.props.match.params.slug)
});
});
}
render() {
// returns the correct data
console.log(this.props.match.params.slug);
const { article } = this.state;
return (
article !== null &&
<div>
<h1>{article.title}</h1>
<p>Tags: {article.tags}</p>
<p>{article.content}</p>
<img src={article.image.url} alt=""/>
</div>
)
}
}
componentDidMount() {
this.loadArticle(this.props.match.params.slug);
}
componentWillReceiveProps(newProps) {
if (this.props.match.params.slug !== newProps.match.params.slug) {
this.loadArticle(newProps.match.params.slug);
}
}