在 parent 组件上设置 属性
Setting a property on a parent component
我正在使用 react-router 和 redux,并且我有以下 App
组件:
export default class App extends Component {
render() {
return (
<div>
<Header />
<PageTitle title="Projects" />
<div className="page-content">
{this.props.children}
</div>
</div>
);
}
}
此组件随后用于 react-route:
export default (
<Route path="/" component={App}>
<IndexRoute component={ProjectsList} />
<Route path="projects/:id" component={ProjectsShow} />
</Route>
);
我想根据我当前正在渲染的路由器组件动态设置 <PageTitle title="Projects" />
组件的 title
属性。
有些组件不能有固定的标题,因为它们取决于我当前显示的项目的信息,所以如果项目名为我的项目,这就是我要显示的标题。
我还使用 redux-promise
来解决我的所有承诺,我需要根据组件上的承诺结果以某种方式更新此外部组件。这是一个例子:
class ProjectsShow extends Component {
static contextTypes = { router: PropTypes.object };
componentWillMount() {
this.props.fetchProject(this.props.params.id);
// I want to set the title of the `PageTitle` component
// when this fetch is resolved
}
// (...)
}
关于如何实现这个的任何建议?
您可以创建一个额外的操作来更改标题、创建一个缩减程序并将结果状态连接到您的组件。
function reducer(state="Default title", action) {
switch SET_TITLE:
return action.title
...
}
然后使用来自 react-redux
的 connect() 包装您的 PageTitle 组件
这正是 redux 擅长的场景。
我正在使用 react-router 和 redux,并且我有以下 App
组件:
export default class App extends Component {
render() {
return (
<div>
<Header />
<PageTitle title="Projects" />
<div className="page-content">
{this.props.children}
</div>
</div>
);
}
}
此组件随后用于 react-route:
export default (
<Route path="/" component={App}>
<IndexRoute component={ProjectsList} />
<Route path="projects/:id" component={ProjectsShow} />
</Route>
);
我想根据我当前正在渲染的路由器组件动态设置 <PageTitle title="Projects" />
组件的 title
属性。
有些组件不能有固定的标题,因为它们取决于我当前显示的项目的信息,所以如果项目名为我的项目,这就是我要显示的标题。
我还使用 redux-promise
来解决我的所有承诺,我需要根据组件上的承诺结果以某种方式更新此外部组件。这是一个例子:
class ProjectsShow extends Component {
static contextTypes = { router: PropTypes.object };
componentWillMount() {
this.props.fetchProject(this.props.params.id);
// I want to set the title of the `PageTitle` component
// when this fetch is resolved
}
// (...)
}
关于如何实现这个的任何建议?
您可以创建一个额外的操作来更改标题、创建一个缩减程序并将结果状态连接到您的组件。
function reducer(state="Default title", action) {
switch SET_TITLE:
return action.title
...
}
然后使用来自 react-redux
的 connect() 包装您的 PageTitle 组件这正是 redux 擅长的场景。