我有一个路由,它接受一个 id 并为每个 id 呈现相同的组件,例如:
<Route path='/:code' component={Card}/>
现在在 Link 标签中,我将一个 id 传递给组件。现在 Card 组件根据传递的 id 获取其他详细信息。但问题是它只为一个 id 呈现,如果我单击返回并转到下一个 id,则不会更新。我搜索并发现可以使用 componentsWillReceiveProps 但在 React 的最新版本中它已被弃用。那么如何做到这一点呢?
我有一个路由,它接受一个 id 并为每个 id 呈现相同的组件,例如:
<Route path='/:code' component={Card}/>
现在在 Link 标签中,我将一个 id 传递给组件。现在 Card 组件根据传递的 id 获取其他详细信息。但问题是它只为一个 id 呈现,如果我单击返回并转到下一个 id,则不会更新。我搜索并发现可以使用 componentsWillReceiveProps 但在 React 的最新版本中它已被弃用。那么如何做到这一点呢?
将当前位置作为组件上的键可以解决问题。
<Route path='/:code' component={(props) => <Card {...props} key={window.location.pathname}/>}/>
我刚刚遇到了类似的问题。我认为您将更新/重新渲染和重新安装混为一谈。当我处理它时,这张关于react生命周期方法的图表帮助了我。
如果你的问题和我的一样,你有一个类似的组件
class Card extend Component {
componentDidMount() {
// call fetch function which probably updates your redux store
}
render () {
return // JSX or child component with {...this.props} used,
// some of which are taken from the store through mapStateToProps
}
}
第一次访问挂载此组件的 url 时,一切正常,然后,当您访问另一个使用相同组件的路由时,没有任何变化。那是因为组件没有被重新安装,它只是因为一些 props 发生了变化而被更新,至少this.props.match.params
正在发生变化。
但是componentDidMount()
在组件更新时不会被调用(见上面的链接)。因此,您不会获取新数据并更新您的 redux 存储。您应该添加一个componentDidUpdate()
功能。这样你就可以在 props 改变时再次调用你的获取函数,而不仅仅是在组件最初安装时。
componentDidUpdate(prevProps) {
if (this.match.params.id !== prevProps.match.params.id) {
// call the fetch function again
}
}
查看 react文档以获取更多详细信息。
我实际上想出了另一种方法来做到这一点。
我们将从您的示例代码开始: <Route path='/:code' component={Card}/>
你想要做的是有<Card>
一个包装组件,功能最好(它实际上不需要任何我认为不需要的状态)并通过传递你的props来渲染你想要渲染的组件{...props}
,以便它得到Router 属性,但重要的是给它一个key
prop 来强制它从头开始重新渲染
例如,我有一些看起来像这样的东西:
<Route exact={false} path="/:customerid/:courierid/:serviceid" component={Prices} />
我希望我的组件在 URL 更改时重新呈现,但仅在 customerid 或 serviceid 更改时重新呈现。所以我做Prices
了一个像这样的功能组件:
function Prices (props) {
const matchParams = props.match.params;
const k = `${matchParams.customerid}-${matchParams.serviceid}`;
console.log('render key (functional):');
console.log(k);
return (
<RealPrices {...props} key={k} />
)
}
请注意,我的密钥仅考虑 customerid 和 serviceid - 当这两个更改时它会重新呈现,但在 courierid 更改时不会重新呈现(如果需要,只需将其添加到密钥中)。并且我的RealPrices
组件受益于仍然传递所有路线props,如历史、位置、匹配等。
在 React Router v4 中在 Router 修复问题后添加 Switch 标签
如果您正在寻找使用钩子的解决方案。
如果您从某个 API 获取数据,那么您可以将该调用包装在一个useEffect
块中并history.location.pathname
作为参数传递给useEffect
.
代码:
import { useHistory } from "react-router";
const App = () => {
const history = useHistory();
useEffect(() => {
//your api call here
}, [history.location.pathname]);
};
useHistory
hook fromreact-router
将给出路径名,因此useEffect
每次更改(url)时都会调用它