【问题标题】:get localstorage value and switch store in redux获取本地存储值并在redux中切换存储
【发布时间】:2018-06-15 04:33:06
【问题描述】:

我在 utils 中有一个功能可以做到这一点:

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

我在这样的组件中调用它

class App extends Component {
  constructor(props) {
    this.role = getUserRole()
  }

  render() {
    console.log(this.role) //admin, member

    return (
      <Provider store={this.role === 'member' ? store : adminStore}>
        <BrowserRouter>
          <div className="App">
            <Switch>
              <Route path="/login" component={Login} />
            </Switch>
          </div>
        </BrowserRouter>
      </Provider>
    )
  }
}

如何在此处切换商店?上面的代码有效,但如果角色是成员,将首先加载 adminStore 然后加载 store。如何防止将 store 和 adminStore 同时加载到我的应用程序中?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux


    【解决方案1】:

    这是因为componentDidMount会在初始渲染后被调用,而在第一次渲染期间this.role将是未定义的。

    class App extends Component {
      componentDidMount() {
        this.role = getUserRole()
        console.log(this.role);   // you will see the correct value
      }
    
      render() {
        console.log(this.role) //undefined
    
        return (
          <div>Hello</div>
        )
      }
    }
    

    为什么它使用 componentWillMount 方法?

    因为该方法在初始渲染之前被调用意味着在第一次触发渲染方法之前。

    解决方案:

    您可以在构造函数中调用该方法,如下所示:

    class App extends Component {
        constructor() {
           super()
           this.role = getUserRole()
        }
        .....
    }
    

    根据Doc

    componentDidMount() 在组件被调用后立即调用 已安装(插入树中)。

    componentWillMount 在挂载之前被调用。这是 在 render() 之前调用。

    【讨论】:

    • 所以解决方案是把它放在构造函数中正确吗?我已经更新了我的问题。
    • 是的,您可以在构造函数中调用该方法。
    • 如果您在构造函数中调用该方法,则只会加载一个存储,因为构造函数在初始渲染之前被调用。并且在第一次渲染期间,该变量将具有正确的值。
    • 在我的情况下,Provider 的 store 道具不要空店,这就是问题所在。
    • @Hoknimo 你能解释一下,不采取空店的意思吗?有什么错误吗?
    【解决方案2】:

    好吧,第一次渲染发生在组件挂载和 componentDidMount 被调用之前,所以第一次渲染确实是未定义的。

    你应该做的是添加一些逻辑来说:

    render() { if (this.role === null) { // Render loading state ... } else { // Render real UI ... } }

    查看here了解更多信息。

    【讨论】:

    • 我知道流程只是在我的情况下我提供了一个值来存储 Provider 的 prop
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 2014-03-25
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2018-10-12
    相关资源
    最近更新 更多