【发布时间】:2020-01-31 20:27:42
【问题描述】:
TL,DR:我需要根据孙子构造函数中的store 值设置默认本地状态值。
render 与 component。 component 让我可以访问孩子构造函数中的商店,render 没有。在 redux 调度中,render 不会重新挂载子进程,component 会执行并擦除子进程的本地状态。
我的应用中有一个子组件可以访问redux 商店。问题是当我在Router -> Route 中使用component={child} 时,没问题。我可以在child 的构造函数中使用商店。但是,我需要在同一个孩子中更新商店 (dispatch),使用 component= 会导致孩子卸载并重新安装,擦除其本地状态。问题在这里:Redux dispatch causing component local state to reset
所以现在我正在使用render={child},但这样做会导致我无法访问我孩子的构造函数中的商店(值为空)。下面是一些示例代码:
Application.jsx
render() {
// location, match, search used for hiding elements logic
const allTabs = ({ location, match, search }) => {
// Parse the query string and look for the "show" keyword (this is arbitrary)
const qs = queryString.parse(location.search, { ignoreQueryPrefix: true });
return (
<div>
{ qs.hideHeader === "1" ? null : <Header environment={config.environment} user={this.props.currentUser.fullName} /> }
{ qs.hideNav === "1" ? null : <NavigationTabs tabList={this.state.tabList} accessPermissions={this.props.currentUser.permission} /> }
{ qs.hideContent === "1" ? null : <TabContent tabList={this.state.tabList} accessPermissions={this.props.currentUser.permission} /> }
{ qs.hideFooter === "1" ? null : <Footer /> }
</div>
);
}
// Place this inside Router and test it. It is not working.... <Route exact path="/t/directLink?showNoHeaderFor=wfPE" component={singleTab} />
return (
<Router>
<div>
{/* when `component` is used, can use store in child constructor */}
{/* when `render` is used, cannot can use store in child constructor */}
{/* when `render` is used, dispatches don't remount component */}
<Route path="/" render={allTabs} />
</div>
</Router>
);
}
TabContent.jsx -> 渲染返回
return (
<div className="tab-content">
<HashRouter>
<Switch>
{this.props.tabList.map(tab => {
return (
{/* i have also tried messing with render/component here, but the problem is probably in Application.jsx */}
<Route key={tab.id} path={`/t/${tab.url}`} component={tab.component} />
);
})}
{ firstTabUrl !== "" ? <Redirect exact from="/" to={`/t/${firstTabUrl}`} /> : null }
</Switch>
</HashRouter>
</div>
);
一个孙子组件,由 TabContent.jsx 呈现
export class PartnershipStructure extends React.Component {
constructor(props) {
super(props);
// the store
const { periods, portfolios, utilityValues } = this.props;
// setting the default value using props
const calendars = periods.calendars(); // <<-- value is null when `render` is used in Application.jsx
注意:我在页面刷新上发现了这个问题。似乎在store 填满时,孙子正在构建。如果我离开选项卡并返回,则问题未观察到。值得注意的是,使用component=,我没有这个问题。但如前所述,component= 会导致调度重新挂载。
【问题讨论】:
标签: javascript reactjs redux react-router