我有一种简单的感觉,但是我有一个动作,如果满足条件,该动作将分派两个动作。
行动
export function changeDateRange({ startDate, endDate }) {
return function reload(dispatch, getState) {
if (!getState().navigation.focused) {
// If our datepicker has closed, reload the data on the page
dispatch(load());
}
dispatch({
type: types.CHANGE_DATE_RANGE,
startDate,
endDate
});
};
}
Run Code Online (Sandbox Code Playgroud)
然后我试图测试load()并用a对其进行了模拟,Jest.fn()但是当我mock.calls.length在分派后登录时是否changeDateRange()等于0?
设定
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
global.mockStore = configureMockStore([thunk]);
Run Code Online (Sandbox Code Playgroud)
测试:
import * as types from '../actionTypes';
import * as changeDateRange from './changeDateRange';
import { load } from '../reporting';
jest.mock('../reporting', …Run Code Online (Sandbox Code Playgroud) 我正在使用 react native 构建一个应用程序,它要求我get request使用令牌在同一个 API 上执行多个操作。
假设网址是这样的
令牌 URL = https://test.co/v1/tokens、API URL 1 =https://test.co/v1/students和 API URL 2 =https://test.co/v1/cars
首先,为了从任一 API URL 获取数据,我是这样写的
示例 students_actions.js
import axios from 'axios';
import { FETCH_STUDENT } from './types';
const TOKEN_URL = '...'
const STUDENT_URL = '...'
export const fetchStudent = (callback) => async (dispatch) => {
axios.post(TOKEN_URL, {
email: 'email',
password: 'password',
role: 'user'
})
.then((response) => {
const accessToken = response.data.token;
//console.log(accessToken);
axios.get(STUDENT_URL, {
headers: { …Run Code Online (Sandbox Code Playgroud) 我目前正在规划一个大规模的 Angular 6 应用程序,并试图找到一种最适合团队需求的方法来处理副作用。
我意识到在 Ngrx 生态系统中最常用的方法是使用ngrx/effects库,我想知道与thunk方法相比使用它有什么优势,thunk方法似乎是 React 最流行的方法应用。
我的想法是将所有引起副作用的逻辑隔离在一个地方,我总是倾向于将它们隔离在 Action Creators 范围内。将所有副作用逻辑移动到不同的“抽象层”感觉就像会增加编写副作用动作的开销,而没有可观的附加值,因为大多数“强烈逻辑”动作用于处理副作用。
有没有其他理由支持效果而不是 thunk?Angular 中的 ngrx 和 React 的经典 Redux 之间有什么根本区别,这使得 ngrx/effect 成为更好的选择吗?
是否可以使用 axios 自动限制所有发送到特定端点列表的请求?也许使用 axios 拦截器?
目前我限制了发送 axios 请求的用户操作,但问题是我必须在任何地方都写这个我有一个用户操作会导致一些 AJAX 请求。像这样
const throttledDismissNotification = throttle(dismissNotification, 1000)
const dismiss = (event: any) => {
throttledDismissNotification();
};
render() {
return (
<Button onClick={dismiss}>Dismiss Notification</Button>
)
}
Run Code Online (Sandbox Code Playgroud)
这会导致很多混乱,我想知道这是否可以自动化。
就像是:
if(request.url in listOfEndpointsToThrottle && request.params in cacheOfPreviousRequestsToThisEndpoint) {
StopRequest();
}
Run Code Online (Sandbox Code Playgroud)
显然这是伪代码,但你明白了。
我有一个运行 redux 和 thunk 的 React 应用程序,它一直运行良好。我需要在页面重新加载时保持存储状态,以便数据不会丢失,因此创建了一个将数据存储在 localstorage 中的函数,然后返回准备添加到 createStore 的数据(https://stackoverflow.com/a/ 45857898/801861)。数据存储工作正常并返回准备设置状态的对象。在 createStore 中添加数据对象时,反应无法编译并出现此错误:
错误:看起来您正在将多个商店增强器传递给 createStore()。这不受支持。相反,将它们组合成一个函数
这是当前代码返回错误:
const store = createStore(reducers, LoadState, applyMiddleware(thunk) );
//Error: It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function
Run Code Online (Sandbox Code Playgroud)
我正在运行的原始代码:
const store = createStore(reducers, applyMiddleware(thunk) );
Run Code Online (Sandbox Code Playgroud)
我试图在我在网上找到的一些类似问题之后解决这个问题,编译但破坏了最初工作正常的站点代码:
const composeEnhancers = LoadState || compose;
const store = createStore(reducers, composeEnhancers( applyMiddleware(thunk) ) );
//Error: Actions must be plain objects. Use custom …Run Code Online (Sandbox Code Playgroud) 我有一个带有 Jest 测试套件的 React 应用程序。应用程序使用 redux,测试套件使用 redux-mock-store。我正在使用 react-thunk 中间件来延迟调度操作,因为应用程序需要与远程 Firebase 数据库同步数据。我希望我的测试套件在向 Redux 分派操作后验证某些条件,如下所示:
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
// This is my custom async action generator.
import { asyncAction } from './some/path';
const createMockStore = configureMockStore([thunk]);
test("Test", (done) => {
const store = createMockStore({});
const data = { ... };
store.dispatch(asyncAction(data)).then(() => {
expect(someCondition);
done();
});
});
Run Code Online (Sandbox Code Playgroud)
该测试使用 Jest 返回的 done 处理程序来等待 store.dispatch 返回的 promise 完成。但是,promise 永远不会执行,测试进入无限循环,Jest 失败并出现以下异常:
Assertion failed: new_time >= loop->time, file c:\ws\deps\uv\src\win\core.c, line 309 …Run Code Online (Sandbox Code Playgroud) 我是 React、Redux 和 JS 的新手。我想知道如何在另一个完成后调度和行动 - 以正确的方式承诺。我的代码实际上有效,但它不断抛出错误:
readingActions.js?14b9:56 Uncaught (in promise) TypeError: dispatch(...).then is not a function(…)
Run Code Online (Sandbox Code Playgroud)
这是我的设置。
这是我的动作创建者,我想要链接的动作以及发生警告的位置。
export function createReading(reading) {
return function (dispatch) {
dispatch({type: CREATE_READING});
return request(
`${API_URL}new`, {method: 'POST', body:JSON.stringify(reading)},
(json) => {( dispatch({type: CREATE_READING_SUCCESS, res: json}).then(dispatch(Notifications.success(showSuccess(json.book.title)))))},
(json) => { dispatch({type: CREATE_READING_ERROR400, res: json}).then(dispatch(Notifications.error(showError(json.error)))) },
(res) => { dispatch({type: CREATE_READING_ERROR500, res: res}) },
(ex) => { dispatch({type: CREATE_READING_FAILURE, error: ex}) },
)
}
}
Run Code Online (Sandbox Code Playgroud)如您所见,问题出在 .then 中,因为我不知道如何正确触发操作。
您还可以看到请求是我的辅助函数,看起来像这样(这里我附加令牌,返回不同的响应):
export function request(url, options, success, error400, error, …Run Code Online (Sandbox Code Playgroud)我在一个在线食品订购应用程序中使用 Redux 和 React。
当用户从他们的购物篮中移除一件商品时,我需要向服务器发出 XHR 请求以计算购物篮的新总价。当这个 XHR 完成时,我更新 redux 商店并呈现新的价格。我正在使用 Redux thunk 来管理这个异步操作。
有一个问题是用户快速连续地从篮子中取出两个物品。用户删除了第一件商品,然后我触发了 XHR 以获得新价格。然后用户单击一个按钮以删除第二个项目,并触发第二个 XHR。
如果第二个 XHR 在第一个 XHR 之前完成,则 UI 将处于不正确的状态 - 将显示仅移除第一个项目的篮子的价格。
为了解决这个问题,我想在用户单击按钮删除第二个项目时取消第一个(飞行中)XHR。要取消第一个 XHR,我需要跟踪 promise 对象(我使用axios来管理 XHR)。
将飞行中的 XHR 存储在 redux 存储中对我来说是有意义的。像这样在 Redux 中存储 promise 是不好的做法吗?这似乎令人不悦——Redux 应该真的只是存储普通数据。
题:
我使用redux-thunk并且我想接收帖子。要接收帖子,我需要获得用户。所以我对我的 thunk 有疑问,在一个 thunk 中获取所有数据是否正确,如果不是如何将其拆分为两个 thunk?
Thunk 示例:
export default group_id => {
return async dispatch => {
const users = await API.get(`/users?group_id=${group_id}`) // get users
const posts = await axios.all([...getPosts(users)]) // get all posts by user ids
dispatch(loadUsersAction(users))
dispatch(loadPostsAction(posts))
}
}
Run Code Online (Sandbox Code Playgroud) I am using Redux Toolkit and TypeScript to create a Todos app. I want to create middleware that will listen for a dispatched action so I can then dispatch async actions.
// listenerMiddleware.ts
import { createListenerMiddleware, addListener } from '@reduxjs/toolkit'
import type { TypedStartListening, TypedAddListener } from '@reduxjs/toolkit'
import type { RootState, AppDispatch } from './store'
export const listenerMiddleware = createListenerMiddleware()
export type AppStartListening = TypedStartListening<RootState, AppDispatch>
export const startAppListening =
listenerMiddleware.startListening as AppStartListening …Run Code Online (Sandbox Code Playgroud) redux-thunk ×10
javascript ×6
redux ×6
react-redux ×5
reactjs ×5
axios ×2
jestjs ×2
angular ×1
api ×1
firebase ×1
ngrx ×1
ngrx-effects ×1
node.js ×1
react-native ×1
redux-store ×1
unit-testing ×1