【发布时间】:2018-07-16 16:58:28
【问题描述】:
我正在尝试结合 react-router v4、react 和 redux。因为 react-router 跟踪 URL,所以我选择将该状态保留在 redux-model 之外。
但是当 react-router 发生路由更改时,我仍然需要一种方法来调度 redux 操作。最好的地方在哪里?
我的第一次尝试是把它放在 react-router 的 Link 的 onClick 属性中:
render() {
// link config
const links = this.props.photo.album( album => {
<Link key={album.name}
to=`/album/${album.name}`
onClick={() => this.props.dispatchAction(album.name)} />
})
// route config
return (
<div>
{links}
<Route path={`/album/:albumName`} component={Album}/>
</div>
)
}
这个想法是,当用户点击一个链接时,dispatchAction() 将更新 redux 状态,然后加载 Album 组件。
问题在于,如果用户直接导航到 URL(例如 /album/a1),则永远不会分派操作,因为从技术上讲,永远不会点击链接。
因此,我删除了 Link 的 onClick 部分,并将 dispatchAction 移至 Album 组件的生命周期方法:
class Album extends Component {
// invoked when user navigates to /album/:albumName directly
componentDidMount() {
this.props.dispatchAction(this.props.match.params.albumName)
}
// invoked whenever the route changes after component mounted
componentWillReceiveProps(nextProps) {
if (this.props.match.params.albumName != nextProps.match.params.albumName) {
this.props.dispatchAction(nextProps.match.params.albumName)
}
....
}
现在,每当安装 Album 组件或更改其属性时,它都会调度 redux-action。这是组合这些库的正确方法吗?
【问题讨论】:
标签: javascript reactjs redux react-router