我有一个用户过滤器组件,单击该组件可以更改路径并设置某些状态。如果我加载浏览器并分别访问每个路径:/
,/female/
,/male
,那么一切都会按预期进行,并显示用户列表。
但是,当我单击按钮并调用router.goTo(views.someRoute)
时,我得到一个错误,提示store.user
未定义:
这是我的view.js
配置:
import React from 'react';
import { Route } from 'mobx-router';
/*
* Components
*/
import Snaproll from './Snaproll/Snaproll'
import RegistrationForm from './RegistionForm'
/*
* Views/Router
*/
const views = {
allUsers: new Route({
path: '/',
component: <Snaproll />,
onEnter: async (route, params, store) => {
console.log(store)
/*
store.user.setGender('all')
if(!store.user.hasUsers) {
await store.user.fetchUsers()
}
*/
}
}),
femaleUsers: new Route({
path: '/female',
component: <Snaproll />,
onEnter: async (route, params, store) => {
store.user.setGender('female')
if(!store.user.hasUsers) {
await store.user.fetchUsers()
}
}
}),
maleUsers: new Route({
path: '/male',
component: <Snaproll />,
onEnter: async (route, params, store) => {
store.user.setGender('male')
if(!store.user.hasUsers) {
await store.user.fetchUsers()
}
}
}),
register: new Route({
path: '/register',
component: <RegistrationForm />
})
};
export default views;
在/
路由中,我设置了一个控制台日志,只是为了查看单击以下按钮之一后商店实际上是否可用。它是未定义的,但是当我在地址栏中手动修复路由时,效果很好。
import React from 'react'
import { observer } from 'mobx-react'
import views from '../views'
const UserFilter = ({ router }) =>
<div className="has-text-centered">
<ul>
<li>
<button onClick={() => router.goTo(views.allUsers)}>All</button>
</li>
<li>
<button onClick={() => router.goTo(views.maleUsers)}>Male</button>
</li>
<li>
<button onClick={() => router.goTo(views.femaleUsers)}>Female</button>
</li>
</ul>
</div>
export default observer(UserFilter)
按下按钮时出现的错误是:
Uncaught (in promise) TypeError: Cannot read property 'user' of undefined
at Route._callee$ (views.js:18)
at tryCatch (runtime.js:62)
at Generator.invoke [as _invoke] (runtime.js:288)
at Generator.prototype.(/anonymous function) [as next] (https://addmysnap.local/app.js:22519:21)
at asyncGeneratorStep (asyncToGenerator.js:3)
at _next (asyncToGenerator.js:25)
at asyncToGenerator.js:32
at new Promise (<anonymous>)
at Route.<anonymous> (asyncToGenerator.js:21)
at Route.onEnter (views.js:17)
我想念什么?
答案 0 :(得分:0)
解决方案是将store
传递给goTo
:
import React from 'react'
import { observer } from 'mobx-react'
import views from '../views'
const UserFilter = ({ store }) =>
<div className="has-text-centered">
<ul>
<li>
<button onClick={() => store.router.goTo(views.allUsers, store.router.currentView.getParamsObj, store)}>All</button>
</li>
<li>
<button onClick={() => store.router.goTo(views.maleUsers, store.router.currentView.getParamsObj, store)}>Male</button>
</li>
<li>
<button onClick={() => store.router.goTo(views.femaleUsers, store.router.currentView.getParamsObj , store)}>Female</button>
</li>
</ul>
</div>
export default observer(UserFilter)