一周前,我们用react和mobx开始了一个新项目,我遇到了和你一样的问题。环顾四周后,我发现最好的方法是使用 react 的context。就是这样:
店铺:stores/Auth.js
import { get, post } from 'axios';
import { observable, computed } from 'mobx';
import jwt from 'jsonwebtoken';
import singleton from 'singleton';
import Storage from '../services/Storage';
class Auth extends singleton {
@observable user = null;
@computed get isLoggedIn() {
return !!this.user;
}
constructor() {
super();
const token = Storage.get('token');
if (token) {
this.user = jwt.verify(token, JWT_SECRET);
}
}
login(username, password) {
return post('/api/auth/login', {
username, password
})
.then((res) => {
this.user = res.data.user;
Storage.set('token', res.data.token);
return res;
});
}
logout() {
Storage.remove('token');
return get('/api/auth/logout');
}
}
export default Auth.get();
注意:我们使用单例来确保它只是一个实例,因为商店可以在反应组件之外使用,例如。routes.js
路线:routes.js
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './App';
import Login from './Login/Login';
import Admin from './Admin/Admin';
import Dashboard from './Admin/views/Dashboard';
import Auth from './stores/Auth'; // note: we can use the same store here..
function authRequired(nextState, replace) {
if (!Auth.isLoggedIn) {
replace('/login');
}
}
export default (
<Route name="root" path="/" component={App}>
<Route name="login" path="login" component={Login} />
<Route name="admin" path="admin" onEnter={authRequired} component={Admin}>
<IndexRoute name="dashboard" component={Dashboard} />
</Route>
</Route>
);
主要成分:App.js
// App.js
import React, { Component } from 'react';
import Auth from './stores/Auth';
export default class App extends Component {
static contextTypes = {
router: React.PropTypes.object.isRequired
};
static childContextTypes = {
store: React.PropTypes.object
};
getChildContext() {
/**
* Register stores to be passed down to components
*/
return {
store: {
auth: Auth
}
};
}
componentWillMount() {
if (!Auth.isLoggedIn) {
this.context.router.push('/login');
}
}
render() {
return this.props.children;
}
}
最后,使用 store 的组件:Login.js
import React, { Component } from 'react';
import { observer } from 'mobx-react';
@observer
export default class Login extends Component {
static contextTypes = {
router: React.PropTypes.object.isRequired,
store: React.PropTypes.object.isRequired
};
onSubmit(e) {
const { auth } = this.context.store; // this is our 'Auth' store, same observable instance used by the `routes.js`
auth.login(this.refs.username.value, this.refs.password.value)
.then(() => {
if (auth.isLoggedIn) this.context.router.push('/admin');
})
.catch((err) => {
console.log(err);
});
e.preventDefault();
}
render() {
return (
<div className="login__form">
<h2>Login</h2>
<form onSubmit={this.onSubmit.bind(this)}>
<input type="text" ref="username" name="username" placeholder="Username" />
<input type="password" ref="password" name="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
</div>
);
}
}
您可以声明新的商店并将它们添加到getChildContext
of 中App.js
,并且当您需要某个商店时,只需store
在组件的 中声明依赖项contextTypes
,然后从this.context
.
我注意到不需要将observable作为 prop 传递,只需拥有@observer
装饰器并在组件中使用任何可观察的值,mobx
然后mobx-react
发挥它们的魔力。
顺便说一句,redux 的<Provider store={myStore}><App /></Provider>
作用与App.js
. https://egghead.io/lessons/javascript-redux-passing-the-store-down-implicitly-via-context
参考: