【问题标题】:React + MobX, user Authantication, render errorReact + MobX,用户身份验证,渲染错误
【发布时间】:2019-03-15 01:51:41
【问题描述】:

我正在使用MobX 进行状态管理,并且我还将一些信息保存在localStorage 中。

这就是我的 mobxStore 的样子:

const hydrate = create({
    storage: localStorage, // or AsyncStorage in react-native; default: localStorage
    jsonify: false  // if you use AsyncStorage, here shoud be true; default: true
})

export class VendorStore {
    @observable vendor = {};
    @persist @observable.ref loginState = localStorage.getItem('loginState');
}

var vendorStore = new VendorStore()
hydrate('vendorStore', vendorStore).then(() => console.log('vendorStore has been hydrated'))

export default vendorStore

这个想法是通过loginState控制页面的重定向

这就是我的Dashboard.js 的样子:

if (vendorStore.loginState === false) { return <Redirect to='/signin' /> }
    if (vendorStore.loginState === true) {
        return (
            <div className="Dashboard">
                <h1>Dashboard</h1>
                <Main />
            </div>
        )

它要么没有按预期工作,要么在loginStatefalse 时不重定向,或者抛出如下反应渲染错误:

react-dom.development.js:57 Uncaught Invariant Violation: Dashboard(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null;

任何帮助将不胜感激,

谢谢

【问题讨论】:

  • 也许使用 if-else 语句?我相信您的空渲染错误可能会发生,因为 loginState 可能是 undefinedtrue/false

标签: javascript reactjs mobx mobx-react


【解决方案1】:

If else 不适用于 jsx,请尝试以下操作

vendorStore.loginState ?  return (
            <div className="Dashboard">
                <h1>Dashboard</h1>
                <Main />
            </div>
        ): return <Redirect to='/signin' /> 

【讨论】:

  • 我也试过了,但问题似乎很棘手。当我使用 localStorage 时,即使状态为“false”,它也会呈现 Dashboard 而不是 Redirect。但是如果我不使用localStorage,并且将初始状态设置为false,每次登录后刷新页面,状态都会切换回false。
【解决方案2】:

这里几乎没有潜在的问题。

首先,您的嵌套 if 可能会导致您出现问题,请尝试更改为:

if (vendorStore.loginState) {
  return (
    <div className="Dashboard">
      <h1>Dashboard</h1>
      <Main />
    </div>
  )
} else {
  return <Redirect to='/signin' />
}

其次,如果您希望 React 响应 loginState 中的更改,那么您需要使用可以提供 loginState 作为 React 支持的东西。因为 vanilla React 只会响应状态/道具的变化。尝试整合https://github.com/mobxjs/mobx-react

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-14
    • 2019-01-22
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多