问题
I would like to structure mobx project to look like redux project. Store configuration in one file, actions in another file, maybe some other logic and reactions in third file.
Also, what is the best practice? To have one store like redux or more. How would I do that (taking out @action from inside a class and dispatching it from another file). Can anybody give some nice examples of structuring their projects?
回答1:
Decorators (@
) are a nice way to use MobX with classes, but you can use MobX without using them at all.
You could structure your application like this, by using the function version of action
:
Example (JSBin)
// state.js
useStrict(true);
const appState = observable({
count: 0,
firstName: 'Igor',
lastName: 'Vuk',
fullName: computed(function() {
return `${this.firstName}-${this.lastName}`;
})
});
// actions.js
const increment = action(function() {
++appState.count;
});
const changeLastName = action(function() {
appState.lastName = 'Stravinskij';
});
// app.js
autorun(() => {
console.log(`${appState.fullName} has been logged in for ${appState.count} seconds`);
});
setInterval(() => {
increment();
}, 1000);
setTimeout(() => {
changeLastName();
}, 3000)
来源:https://stackoverflow.com/questions/46840028/structure-mobx-project-like-redux