Redux를위한 것이고 Mobx를 위해 수행하는이 https://github.com/elgerlambert/redux-localstorage을 근본적으로 수행하려고합니다. 그리고 바람직하게는 sessionStorage를 사용하고 싶습니다. 최소한의 상용구만으로도이를 달성 할 수있는 쉬운 방법이 있습니까?세션 저장 영역에 Mobx 상태를 저장하는 방법
3
A
답변
4
가장 쉬운 방법은 관찰 가능한 속성이 변경 될 때마다 mobx "자동 실행"을 트리거하는 것입니다. 그렇게하려면 my answer to this question을 따라갈 수 있습니다. 하지만 반드시, https://mobx.js.org/best/store.html
이 값의 변화를 검출하는 청소기 방법을 보여줍니다
function autoSave(store, save) {
let firstRun = true;
mobx.autorun(() => {
// This code will run every time any observable property
// on the store is updated.
const json = JSON.stringify(mobx.toJS(store));
if (!firstRun) {
save(json);
}
firstRun = false;
});
}
class MyStore {
@mobx.observable prop1 = 999;
@mobx.observable prop2 = [100, 200];
constructor() {
this.load();
autoSave(this, this.save.bind(this));
}
load() {
if (/* there is data in sessionStorage */) {
const data = /* somehow get the data from sessionStorage or anywhere else */;
mobx.extendObservable(this, data);
}
}
save(json) {
// Now you can do whatever you want with `json`.
// e.g. save it to session storage.
alert(json);
}
}
2
여기에서 예를 게시 :
은 당신이 시작하는 데 도움이해야 여기에 몇 가지 예제 코드를 놓을 게요 로컬 저장소.
import {observable, autorun} from 'mobx';
import uuid from 'node-uuid';
export class TodoStore {
authorStore;
transportLayer;
@observable todos = [];
@observable isLoading = true;
constructor(transportLayer, authorStore) {
this.authorStore = authorStore; // Store that can resolve authors for us
this.transportLayer = transportLayer; // Thing that can make server requests for us
this.transportLayer.onReceiveTodoUpdate(updatedTodo => this.updateTodoFromServer(updatedTodo));
this.loadTodos();
}
/**
* Fetches all todo's from the server
*/
loadTodos() {
this.isLoading = true;
this.transportLayer.fetchTodos().then(fetchedTodos => {
fetchedTodos.forEach(json => this.updateTodoFromServer(json));
this.isLoading = false;
});
}
/**
* Update a todo with information from the server. Guarantees a todo
* only exists once. Might either construct a new todo, update an existing one,
* or remove an todo if it has been deleted on the server.
*/
updateTodoFromServer(json) {
var todo = this.todos.find(todo => todo.id === json.id);
if (!todo) {
todo = new Todo(this, json.id);
this.todos.push(todo);
}
if (json.isDeleted) {
this.removeTodo(todo);
} else {
todo.updateFromJson(json);
}
}
/**
* Creates a fresh todo on the client and server
*/
createTodo() {
var todo = new Todo(this);
this.todos.push(todo);
return todo;
}
/**
* A todo was somehow deleted, clean it from the client memory
*/
removeTodo(todo) {
this.todos.splice(this.todos.indexOf(todo), 1);
todo.dispose();
}
}
export class Todo {
/**
* unique id of this todo, immutable.
*/
id = null;
@observable completed = false;
@observable task = "";
/**
* reference to an Author object (from the authorStore)
*/
@observable author = null;
store = null;
/**
* Indicates whether changes in this object
* should be submitted to the server
*/
autoSave = true;
/**
* Disposer for the side effect that automatically
* stores this Todo, see @dispose.
*/
saveHandler = null;
constructor(store, id=uuid.v4()) {
this.store = store;
this.id = id;
this.saveHandler = reaction(
// observe everything that is used in the JSON:
() => this.asJson,
// if autoSave is on, send json to server
(json) => {
if (this.autoSave) {
this.store.transportLayer.saveTodo(json);
}
}
);
}
/**
* Remove this todo from the client and server
*/
delete() {
this.store.transportLayer.deleteTodo(this.id);
this.store.removeTodo(this);
}
@computed get asJson() {
return {
id: this.id,
completed: this.completed,
task: this.task,
authorId: this.author ? this.author.id : null
};
}
/**
* Update this todo with information from the server
*/
updateFromJson(json) {
// make sure our changes aren't send back to the server
this.autoSave = false;
this.completed = json.completed;
this.task = json.task;
this.author = this.store.authorStore.resolveAuthor(json.authorId);
this.autoSave = true;
}
dispose() {
// clean up the observer
this.saveHandler();
}
}
1
내 코드는 localStorage 만 지원하지만 아주 쉽게 수정할 수 있어야합니다.
0
당신이 자신에 의해 작성되어 mobx-sync을 시도 할 수 있음.
관련 문제
- 1. Google 로그인, 세션 상태를 저장하는 방법?
- 2. 세션 상태를 저장하는 방법은 무엇입니까?
- 3. 세션 상태를 캡처하는 방법
- 4. sqlserver를 사용하여 세션 상태를 저장하는 방법은 무엇입니까?
- 5. SharePoint를 사용하여 세션 상태를 저장하는 옵션
- 6. 세션 상태를 저장하는 가장 좋은 옵션
- 7. NSUserdefaults에 UISegmentedControl 상태를 저장하는 방법
- 8. 활동 상태를 저장하는 방법
- 9. 의도 상태를 저장하는 방법
- 10. Heroku - 상태를 저장하는 방법
- 11. ImageButton의 상태를 저장하는 방법
- 12. JSF - 세션 시간이 초과되면 managedBean 상태를 저장하는 방법?
- 13. 세션 저장소와 HTML 데이터 특성을 사용하여 DOM 상태를 저장하는 방법
- 14. DB 저장 영역에 사용자 정의 세션 상태 제공자가 필요합니까?
- 15. 상태를 asp.net에 저장 MVC
- 16. 안드로이드 서비스에서 상태를 저장하는 방법
- 17. 조각을 편집하고 상태를 저장하는 방법?
- 18. 날짜 피커의 상태를 저장하는 방법
- 19. URL에 앱 상태를 저장하는 방법
- 20. 현재 작업 상태를 저장하는 방법?
- 21. 내 활동 상태를 저장하는 방법
- 22. 안드로이드에 조각의 상태를 저장하는 방법?
- 23. extjs 그리드에서 상태를 저장하는 방법
- 24. 파이썬에서 실행 상태를 저장하는 방법
- 25. 내 조각의 상태를 저장하는 방법
- 26. CGAffineTransformMake - UIimageview의 상태를 저장하는 방법
- 27. Silverlight의 상태를 저장하는 쉬운 방법
- 28. Mobx 관찰 가능 객체를 문자열로 변환하는 방법
- 29. MobX + 반작용 - 나는 MobX 놀아 된
- 30. 앱의 상태를 저장하는 경우
감사합니다. 페이지 새로 고침시 상태를 어떻게 다시로드합니까? –
생성자에서'autoSave()'를 호출하기 전에 sessionStorage에서 읽고 저장소 인스턴스의 값을 설정할 수 있습니다. –
방금보다 완벽한 솔루션을 제공하기 위해 내 대답을 편집했습니다. 물론 당신은 여전히 당신의 사건에 효과가 있도록 약간의 변화를 줄 필요가 있습니다. 그러나 이것이 당신이 시작하는 데 도움이되기를 바랍니다. –