在单个反应组件中,用户单击按钮 => 调用方法 => 触发操作 => 异步获取 => 减速器更新状态 => 组件接收新道具。
回到触发我一直使用的操作的原始组件中:
componentWillReceiveProps(nextProps){
if(nextProps.someProp !== this.props.someProp){
//ok new prop is here
this.someMethod(nextProps.someProp);
}
}
Run Code Online (Sandbox Code Playgroud)
我是否以正确的方式解决这个问题?
它看起来有点笨拙,并且作为一种回调机制与用户操作或状态变化分离。一旦有几个这样的组件,它只会使遵循组件的逻辑流程变得更加困难,我有一个包含其中 3 个的组件,并且已经认为这并不容易推理,尤其是当它们是相关流程的一部分时 a > b > C 。我已经结束了这种事情:
componentWillReceiveProps(nextProps){
if(this.patchJavaScriptWillLoad(nextProps)){
this.createPatchInstance();
// method fires an action which will also result in state change that triggers the below.
}
if(this.patchInstanceWillBeReady(nextProps)){
this.startPatchAudio(nextProps.webAudioPatch.instance);
// method fires an action which will also result in state change that triggers the below.
}
if(this.patchParametersWillChange(nextProps)){
this.updateWebAudioPatchParameters(nextProps.webAudioPatchParameters);
}
}
// abstracted away …Run Code Online (Sandbox Code Playgroud) 我目前正在做的是:
export type Action =
{ type: 'FOO' }
| { type: 'BAR' }
export type Thunk = (dispatch: Dispatch, getState: GetState) => Action | Thunk
export type Dispatch = ReduxDispatch<Action> & (action: Thunk) => void
Run Code Online (Sandbox Code Playgroud)
但如果你直接派遣store,那将无法重新创建store:
export type Store = ReduxStore<State, Action>
一般来说,我的thunk解决方案似乎还有其他一些小问题.有没有人有工作库定义redux-thunk?我找不到任何地方.
在我的项目中,Redux Thunk用于将所有异步函数保留在动作创建器中.
现在我正在尝试将Apollo GraphQL添加到我的项目中,除了将突变添加到我的功能组件并在那里调用它之外,一切都运行良好,它打破了redux thunk架构.
怎么解决?我想我可以创建新的动作创建器方法并将突变传递给它们,但它很快就会变成样板,而这对我来说似乎不是一个好的解决方案.
我有一种简单的感觉,但是我有一个动作,如果满足条件,该动作将分派两个动作。
行动
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) useHistory ()挂钩在我的项目中不起作用。我把它放在不同的组件中,但它们都不起作用。我正在使用“react-router-dom”:“^5.2.0”,
import {useHistory} from 'react-router-dom'
const history = useHistory()
const logout = () => {
toggleMenu()
setUser(null)
dispatch({type: 'LOGOUT'})
history.push('/')
}
Run Code Online (Sandbox Code Playgroud)
而且在行动中它也不起作用
export const signin = (formdata, history, setError) => async (dispatch) => {
try {
const {data} = await API.signIn(formdata)
if(data.error){
setError(data.message)
}else{
dispatch({type: SIGNIN, data})
history.push('/dashboard')
}
} catch (error) {
setError(error)
console.log(error)
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 router.js 文件
const Router = () => {
const user = JSON.parse(localStorage.getItem('profile'))
return (
<BrowserRouter>
<>
{user && <Navigation/>}
<Switch> …Run Code Online (Sandbox Code Playgroud) redux-thunk ×10
reactjs ×7
react-redux ×5
redux ×5
javascript ×3
jestjs ×2
angular ×1
api ×1
axios ×1
firebase ×1
ngrx ×1
ngrx-effects ×1
node.js ×1
react-native ×1
redux-store ×1
unit-testing ×1