所以,基本上我有多个嵌套路由,比如 /:platform/:account/products/:tab/:productId/summary
.
一切正常,直到我的实际单个产品组件,但 react-router 在我的单个产品选项卡中停止正常工作。
我有一个带有选项卡(路由)的产品 View ,当单击一个项目时,有一个弹出窗口是单个产品 View ,其中还有 3 个选项卡。
我的产品的子路由正在更新,但仅限于下一个渲染周期。
(路由更改为
/:platform/:account/products/:tab/:productId/prices
) (路由更改为
/:platform/:account/products/:tab/:productId/summary
) (路由更改为
/:platform/:account/products/:tab/:productId/translations
) (完全没有路线变化)
我已经与这个斗争了 4 个多小时,我检查了我是否有任何
PureComponent
在我的树中,我使用了 withRouter
几乎无处不在,我还检查了我的产品组件是否没有更新(也许我的主 View 组件阻止了更新),但一切似乎都很好,新 Prop 是正确的。我也尝试使用
{ pure: false }
在 connect()
但没有任何帮助。我也删除了这个
localize
HOC 以防万一,但这并没有解决它。版本
4.2.0
示例代码
这是我的组件中精简的渲染方法:
class ProductView extends Component {
componentWillReceiveProps() {
console.log("UPDATED PRODUCT TAB")
}
render() {
const { match, history, translate, lang, loading, data } = this.props
console.log(match)
return (
<Modal>
<TabList>
<TabItem>
<NavLink
activeClassName="active"
to={{
pathname: `/${match.params.platform}/${match.params.account}/products/${match.params.tab}/${match.params.productId}/summary`,
search: location.search,
}}
>
{translate("Summary")}
</NavLink>
</TabItem>
<TabItem>
<NavLink
activeClassName="active"
to={{
pathname: `/${match.params.platform}/${match.params.account}/products/${match.params.tab}/${match.params.productId}/prices`,
search: location.search,
}}
>
{translate("Prices")}
</NavLink>
</TabItem>
<TabItem>
<NavLink
activeClassName="active"
to={{
pathname: `/${match.params.platform}/${match.params.account}/products/${match.params.tab}/${match.params.productId}/translations`,
search: location.search,
}}
>
{translate("Translations")}
</NavLink>
</TabItem>
</TabList>
<Switch>
<Route path="/:platform/:account/products/:tab/:id/summary" component={Summary} />
<Route path="/:platform/:account/products/:tab/:id/prices" component={Prices} />
<Route path="/:platform/:account/products/:tab/:id/translations" component={Translations} />
</Switch>
</Modal>
)
}
}
const mapStateToProps = state => (...)
const mapDispatchToProps = dispatch => (...)
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps,
)(localize("translate")(ProductView)))
到达产品组件的路径如下所示:
<Route exact path="/:platform/:account/products/:tab/:productId/:productTab" component={ProductView} />
添加或删除 :productTab
没什么区别。在具有此产品路线的组件内,我还有其他
NavLinks
选项卡和路由器工作正常。奇怪的是,组件一直更新到我的产品路线,并带有正确的
match
props,但那些子 Routes,包括 NavLinks 只在再次点击后更新。最佳答案
如果您使用嵌套 Route
或 NavLink
(Route 的包装器),您需要使用 Switch
(为方便起见)包装所有模态内容(或至少是使用 Route/NavLink 的部分)。
const location = (this. - if you component is not a function)props.location;
<Switch location={location}>
<NavLink ... />
<Route ... />
</Switch>
这将确保该位置将被更新。
react-modal
不干扰用户组件的更新。 location
路由接收来自 getChildContext()
,它只在 react 组件生命周期之后更新。通过在 render()
上切换位置,上下文将是新的,它将被赋予子级路由。它会按预期工作。
关于reactjs - React Router 仅在第二次点击后更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46338169/