本文整理匯總了TypeScript中redux.Store.subscribe方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Store.subscribe方法的具體用法?TypeScript Store.subscribe怎麽用?TypeScript Store.subscribe使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類redux.Store
的用法示例。
在下文中一共展示了Store.subscribe方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: return
return (store: Store<FullState>) => {
const payload = keeps.reduce(
(action, { key, storage, load }) => ({ ...action, [key]: load(key, storage), }),
{}
);
store.dispatch({
payload,
type: HYDRATE
});
const results: { [key: string]: any; } = {};
store.subscribe(() => {
const state = store.getState();
for (const { key, selector, storage, save } of keeps) {
const result = selector(state);
if (result !== results[key]) {
results[key] = result;
save(key, result, storage);
}
}
});
};
示例2: subscribeToStateChange
public subscribeToStateChange(
listener: Listener,
options: { handlerIds: string[] | undefined } = { handlerIds: undefined },
): Unsubscribe {
const { handlerIds } = options
invariant(typeof listener === 'function', 'listener must be a function.')
invariant(
typeof handlerIds === 'undefined' || Array.isArray(handlerIds),
'handlerIds, when specified, must be an array of strings.',
)
let prevStateId = this.store.getState().stateId
const handleChange = () => {
const state = this.store.getState()
const currentStateId = state.stateId
try {
const canSkipListener =
currentStateId === prevStateId ||
(currentStateId === prevStateId + 1 &&
!areDirty(state.dirtyHandlerIds, handlerIds))
if (!canSkipListener) {
listener()
}
} finally {
prevStateId = currentStateId
}
}
return this.store.subscribe(handleChange)
}
示例3: didChangeSharedState
didChangeSharedState (fn: (state: SharedState) => void) {
this.store.subscribe(() => {
this.events.emit(STATE_UPDATED_EVENT)
this.getSharedState().then(sharedState => {
fn(sharedState)
})
})
}
示例4: trySubscribe
public trySubscribe() {
if (!this.unsubscribe) {
this.unsubscribe = this.parentSub
? this.parentSub.addNestedSub(this.onStateChange)
: this.store.subscribe(this.onStateChange);
this.listeners = createListenerCollection();
}
}
示例5: next
return next => (reducer, initialState: LocalStorage, enhancer) => {
const store: Store<LocalStorage> = next(reducer, initialState, enhancer)
const throttleMs = 1000
store.subscribe(
_.throttle(() => {
saveToLocalStorage(store.getState())
}, throttleMs)
)
return store
}
示例6: it
it("doesn't sync if the uiData registration_synchronized value is true", function (done) {
assert(listener.notCalled);
fetchMock.mock({
matcher: uiDataFetchURL,
response: () => {
let body = generateGetUIDataResponse({
[KEY_REGISTRATION_SYNCHRONIZED]: true,
});
return { body };
},
});
fetchMock.mock({
matcher: clusterFetchURL,
response: () => {
const encodedResponse = protos.cockroach.server.serverpb.ClusterResponse.encode({ cluster_id: CLUSTER_ID }).finish();
return {
body: api.toArrayBuffer(encodedResponse),
};
},
});
fetchMock.mock({
matcher: registrationFetchURLPrefixMatcher,
response: () => {
done(new Error("Should not have tried to contact the registration server."));
},
});
// Trigger the store subscription.
store.dispatch({ type: null });
assert(listener.called);
// Watch the state and complete the test successfully if we last a tick with
// the expected information.
let timeout: number;
store.subscribe(() => {
let state = store.getState();
clearTimeout(timeout);
if (state.cachedData.cluster.data &&
state.cachedData.cluster.data.cluster_id &&
state.uiData[KEY_REGISTRATION_SYNCHRONIZED] &&
state.uiData[KEY_REGISTRATION_SYNCHRONIZED].data
) {
assert.lengthOf(fetchMock.calls(uiDataFetchURL), 1);
assert.lengthOf(fetchMock.calls(clusterFetchURL), 1);
assert.lengthOf(fetchMock.calls(registrationFetchURLPrefixMatcher), 0);
timeout = setTimeout(() => done());
}
});
});
示例7: subscribeToOffsetChange
public subscribeToOffsetChange(listener: Listener): Unsubscribe {
invariant(typeof listener === 'function', 'listener must be a function.')
let previousState = this.store.getState().dragOffset
const handleChange = () => {
const nextState = this.store.getState().dragOffset
if (nextState === previousState) {
return
}
previousState = nextState
listener()
}
return this.store.subscribe(handleChange)
}
示例8: fromJS
const apiHandler = (store: Store<AppState>): void => {
let prevState: any = fromJS({});
store.subscribe(throttle((): void => {
const state = store.getState(); // The state is Immutable Map
if (state.get("isLoading") === true || state.get("valid") === false) {
return void 0;
}
const prevFmtString = (prevState.get("input") || "").split(" ")[0];
const currFmtString = (state.get("input") || "").split(" ")[0];
if (
typeof prevState.get === "function" &&
state.get("input").length > 0 &&
state.get("hexData").length > 0 &&
(
prevFmtString !== currFmtString ||
prevState.get("hexData") !== state.get("hexData")
)
) {
store.dispatch(actions.startLoading());
const body: APIBody = {
formatString: state.get("input"),
input: state.get("hexData"),
};
request.post(API_PATH, body)
.then((res) => {
let data = res.data;
if (typeof data === "string") {
data = JSON.parse(`${data}`);
}
store.dispatch(actions.updateResults(data.results));
store.dispatch(actions.stopLoading());
})
.catch((err: AxiosError) => {
const errorMsg = (err.response ? err.response.data.error : err.message) ||
err.message ||
"Unknown Error";
store.dispatch(actions.stopLoading());
store.dispatch(actions.apiError(errorMsg));
});
}
prevState = state;
}, REQUEST_INTERVAL));
};
示例9: observeStore
export function observeStore(store:Store<any>, ...args) {
let onChange = args.pop();
let selectors = args;
let currentState;
function handleChange() {
const nextState = _.map(selectors, f => f(store.getState()));
const stateChanged = _(nextState)
.zip(currentState)
.some(([x, y]) => (x !== y));
if (stateChanged) {
currentState = nextState;
onChange(...currentState);
}
}
let unsubscribe = store.subscribe(handleChange);
handleChange();
return unsubscribe;
}
示例10: clearTimeouts
const exampleHandler = (store: Store<AppState>): void => {
let prevState: string = "";
store.subscribe((): void => {
const state = store.getState(); // The state is immutable Map.
const example = state.get("example");
if (!example || example === prevState) {
if (prevState && !example) {
prevState = "";
clearTimeouts(_timerRef);
}
return void 0;
}
if (example && example !== prevState) {
prevState = example;
let value = "";
let filter = "";
if (example === "random") {
const _arr = new Uint32Array(120);
(window || global).crypto.getRandomValues(_arr);
_arr.forEach((item) => value += item.toString(16));
filter = "b32B32H16H16f2x128a32 bin Bin Hex hex float ascii";
_exampleReplayer(value, filter, store);
return void 0;
}
if (examples.indexOf(example) > -1) {
store.dispatch(actions.startLoading());
// Cancel inflight request (if any)
if (_cancelTokens.length) {
cancelRequests();
}
const cancelSource = axios.CancelToken.source();
_cancelTokens.push(cancelSource);
fetchExample(example, cancelSource, store);
return void 0;
}
}
});
};