我有一个类似于以下Store
类的MobX商店。当我想访问this.user.permits.db
时,收到this.user
未定义的错误。我想知道为什么我无法访问@observable user
。
src/ui/store/store.js
档案:
import { action, observable } from 'mobx'
import { useStrict } from 'mobx';
useStrict(true);
class Store {
constructor(){
//
}
@observable user
@action setUser=(user)=>{
this.user=user
}
@observable menus=[
{menu1: 'DATABASE',
/*menu2s: ['PC', 'NETWORK', 'TEL', 'PTT'],*/ //-> this line works fine
menu2s: this.user.permits.db, //-> this line gives an error: Cannot read property 'permits' of undefined
}
]
}
export default new Store
从src/ui/ui.js
导入商店的
store.js
文件:
import React from 'react'
import ReactDOM from 'react-dom'
import Layout from './components/layout.js'
import Store from './store/store.js'
//user comes from HTTP GET request
Store.setUser(user)
ReactDOM.render(<Layout store={Store}/>,document.getElementById('ui'))
src/views/profile.ejs
文件,将user
传递给JavaScript:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>User profile</title>
<link href="/css/style.css" rel="stylesheet" type="text/css">
</head>
<!--
Pass variables from http GET to JavaScript
also block script injection attacks
ref: https://stackoverflow.com/a/16098699/7312233
-->
<script>
function htmlDecode(input){
var e=document.createElement('div');
e.innerHTML=input;
return e.childNodes.length===0?"":e.childNodes[0].nodeValue;
}
var user=JSON.parse(htmlDecode("<%= JSON.stringify(user) %>"));
</script>
<div id="ui"></div>
<script src="/js/ui.bundle.js"></script>
</html>
CouchDB用户数据库上的示例用户文档上的
permits
字段定义如下:
更新:
同样this也应该更正。
答案 0 :(得分:1)
this.user
,因此this.user.permits
会引发错误。你可以这样做:
class Store {
@observable user
@observable menus = []
@action setUser = (user) => {
this.user = user
this.menus.push({
menu1: 'DATABASE',
menu2s: this.user.permits.db
})
}
}