使用redux

时间:2018-06-15 09:22:11

标签: javascript reactjs redux

我的应用程序有2个方面,第一方是客户端应用程序,第二方是管理仪表板应用程序。为了让它干,我决定在提供商的基础上通过用户角色的商店,这样我就不必拥有2套路由器。

class App extends Component {
  constructor(props) {
    super(props)

    this.role = getUserRole() //get role from localstorage
  }

  renderSwitchProvider = store => (
    <Provider store={store}>
      <BrowserRouter>
        <div className="App">
          <Switch>
            <Redirect exact from="/" to="/dashboard" />
            <Auth path="/dashboard" component={Dashboard} />

            <Route path="/login" component={Login} />
            <Route path="/signup" component={Signup} />
          </Switch>
        </div>
      </BrowserRouter>
    </Provider>
  )

  render() {
    if (this.role === 'member') {
      return this.renderSwitchProvider(store)
    } else if (this.role === 'admin') {
      return this.renderSwitchProvider(adminStore)
    }

    return null // problem is here
  }
}

export default App

但我错了

Could not find "store" in either the context or props of "Connect(LoginForm)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(LoginForm)".

我的getUserRole会这样做

export function getUserRole() {
  return (
    localStorage.getItem('token') &&
    jwtDecode(localStorage.getItem('token')).role
  )
}

2 个答案:

答案 0 :(得分:0)

问题可能来自getUserRole()这是一个阻塞任务,这会返回一个null,而角色不应为null。

我的建议是拥有APP组件,该组件可解析getUserRole()的值,并根据{{1}的结果返回AdminUser组件}}

getUserRole()组件中删除redux商店实施,并将实施放在单独的AppAdmin组件中。

答案 1 :(得分:0)

正如您所说,有两个方clientadmin

因此,您可以假设存储实现的默认值。

假设您始终希望默认加载client商店。

然后渲染应该是,

render() {

    if (this.role === 'admin') {
      return this.renderSwitchProvider(adminStore)
    }else if(this.role === 'member'){

        return this.renderSwitchProvider(store)
    }



}