【问题标题】:react-router Link calling Redux Actionreact-router 链接调用 Redux Action
【发布时间】:2017-07-21 02:49:56
【问题描述】:

我在 React 中有一个带有 Log out 选项的菜单。我将会话状态保存在 Redux 存储中。当我点击Log out 选项时,我想调度一个操作来销毁商店中的会话,并且应用程序将呈现隐藏任何非公共 UI 的内容。

这是我在 Menu 组件中的 render() 方法:

render() {
    const { customer } = this.props

    const options = customer.isLoggedIn ? [
        { key: 'p1', name: 'Private Page 1', ref: '/private-page-1' },
        { key: 'p2', name: 'Private Page 2', ref: '/private-page-2' },
        { key: 'l', name: 'Logout', ref: '/' },
    ] : [
        { key: 'l', name: 'Login', ref: '/' },
    ]

    return (
        <div className="App-menu">
            <ul>
                {
                    options.map( ( opt ) => {
                        return (
                            <li key={ opt.key }>
                                <Link to={ opt.ref }>{ opt.name }</Link>
                            </li>
                        )
                    } )
                }
            </ul>
        </div>
    )
}

修改 Store 状态是否比在 Link 组件中添加和onClick 处理程序以进行注销更好?

使用 React+Redux 遵循单向数据流最佳实践的最佳方法是什么?

谢谢! :)

【问题讨论】:

    标签: javascript reactjs redux react-router


    【解决方案1】:

    嗯,还有更多选择:

    如果你有一些你必须留下的路线,如果一个人正在注销,有些你必须重定向到'/'(例如:/about -> /about 但/private -> /)所以你可能应该使用@ 987654321@ 而不是 Link 并在删除存储后处理一些 &lt;Redirect /&gt;history.push() 基于状态更改和 location.pathname

    如果您想在每次注销时重定向到“/”,那么我会使用&lt;Link to='/?logout=true'&gt;logout&lt;/Link&gt; 执行此操作,然后处理擦除状态并重定向回“/”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 2018-01-07
      • 2019-08-24
      • 2019-04-06
      • 2019-01-24
      • 2016-11-17
      • 2018-10-16
      相关资源
      最近更新 更多