gpt4 book ai didi

javascript - 如何使用指向相同 URL 的 React-Router 重新渲染组件

转载 作者:行者123 更新时间:2023-12-03 14:22:32 25 4
gpt4 key购买 nike

为了简单起见,详细信息页面根据 URL 中的电影 ID 获取挂载数据,该 ID 来自路由中的 path='movie/:id'。

它的子项称为“推荐”,它会再次根据当前 URL 向您显示推荐的电影。

class MovieDetailPage extends React.Component {

// Fetch movies and cast based on the ID in the url
componentDidMount() {
this.props.getMovieDetails(this.props.match.params.id)
this.props.getMovieCast(this.props.match.params.id)
}



render() {
<div>
Movies here
</div>
<Recommended id={this.props.match.params.id}/>
}
}

推荐组件也会根据当前电影获取数据,并生成另一个指向另一部电影的标签。

class Recommended extends React.Component {

componentDidMount() {
this.props.getRecommended(this.props.id)
}

render() {
return (
<>
<Category title={'Recommended'}></Category>
<div className="movies">
{
this.props.recommended.map((movie) => {
return (
<Link key={movie.id} to={`movie/${movie.id}`} className="movies__item">
<img
key={movie.id}
src={`https://image.tmdb.org/t/p/w342${movie.poster_path}`}
className="movies__item-img"
alt={`A poster of ${movie.title}`}
>
</img>
</Link>
)
})
}
</div>
</>
)
}
}

现在,当单击推荐组件中生成的链接时,如何触发父组件的另一个渲染? URL 正在更改,但这不会像我想要的那样触发渲染。

更新:

<Route 
path="/movie/:id"
render={(props) => (
<MovieDetailPage key={props.match.params.id}
{...props}
)}
/>

这次我传入了一个唯一的 key ,触发了页面的重新渲染。我之前尝试过,但我可能搞砸了语法。

这篇文章让我找到了正确的方向:Force remount component when click on the same react router Link multiple times

最佳答案

向页面添加键

如果您更改路线,但您的页面未获取其“安装”数据,那么您应该向页面添加一个键。这将导致您的页面重新渲染并使用新 ID 挂载并再次获取数据。

您可以阅读有关 react 键的更多信息 here

一个键告诉 React 这是一个特定的组件,这就是为什么你会在列表中看到它们。通过更改页面上的键,您可以告诉 React 这是组件的新实例并且已更改。这将导致重新安装。

类组件示例

class MyPage extends React.Component {
componentDidMound() {
// this will fire each time the key changes since it triggers a mount
}

render() {
return (
<div key={props.pageId}>
{/* component stuff */}
</div>
)
}
}

功能组件示例

const MyPage = (props) => {
React.useEffect(() => {
// this will fire each time the key changes
}, []);

return (
<div key={props.pageId}>
{/* component stuff */}
</div>
)
}

关于javascript - 如何使用指向相同 URL 的 React-Router <Link> 重新渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60416677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com