Redux:可重用的操作
我有一个动作,使用了重击,看起来是这样的:Redux:可重用的操作,redux,Redux,我有一个动作,使用了重击,看起来是这样的: export function fetchData(query) { return dispatch => { return fetch(`http://myapi?query=${query}` ,{mode: 'cors'}) .then(response => response.json()) .then(json => { dispatch(someOtherAction(json)) })
export function fetchData(query) {
return dispatch => {
return fetch(`http://myapi?query=${query}` ,{mode: 'cors'})
.then(response => response.json())
.then(json => { dispatch(someOtherAction(json)) })
}
}
}
然后我的someOtherAction
实际更新状态:
export function someOtherAction(data) {
return {
action: types.SOME_ACTION,
data
}
}
但是我希望fetchData
action creator可以重用,这样我的应用程序的不同部分就可以从myapi
中获取数据,然后基于此拥有不同的状态部分
我想知道重用此操作的最佳方法是什么?是否可以将第二个参数传递给myfetchData
action creator,该参数规定在成功获取时调用哪个操作:
export function fetchData(query, nextAction) {
return dispatch => {
return fetch(`http://myapi?query=${query}` ,{mode: 'cors'})
.then(response => response.json())
.then(json => { dispatch(nextAction(json)) })
}
}
}
还是有一种公认的方式来做这类事情 我使用中间件来实现这一点。我在那里定义了fetch调用,然后在我的操作中发送要获取的URL和完成后要分派的操作。这将是一个典型的获取操作:
const POSTS_LOAD = 'myapp/POST_L';
const POST_SUCCESS = 'myapp/POST_S';
const POST_FAIL = 'myapp/POST_F';
export function fetchLatestPosts(page) {
return {
actions: [POSTS_LOAD, POST_SUCCESS, POST_FAIL],
promise: {
url: '/some/path/to/posts',
params: { ... },
headers: { ... },
},
};
}
调用该操作时,POST_LOAD
操作将在执行获取请求之前由中间件自动分派。如果一切顺利,POST\u SUCCESS
操作将与json响应一起调度,如果出现问题,POST\u FAIL
操作将由中间件调度
所有的魔法都在中间件中!与此类似:
export default function fetchMiddleware() {
return ({ dispatch, getState }) => {
return next => action => {
if (typeof action === 'function') {
return action(dispatch, getState);
}
const { promise, actions, ...rest } = action;
if (!promise) {
return next(action);
}
const [REQUEST, SUCCESS, FAILURE] = actions;
next({ ...rest, type: REQUEST }); // <-- dispatch the LOAD action
const actionPromise = fetch(promise.url, promise); // <-- Make sure to add the domain
actionPromise
.then(response => response.json())
.then(json => next({ ...rest, json, type: SUCCESS })) // <-- Dispatch the success action
.catch(error => next({ ...rest, error, type: FAILURE })); // <-- Dispatch the failure action
return actionPromise;
};
};
}
我希望这有帮助 看起来你无法将其他参数传递给操作。我有一些非常类似的东西被砍掉了。我还执行了一个
nextErrorAction
,作为fetchData
的附加参数。此外,当状态代码为2xx时,我还返回一个承诺和分派(nextAction(data))
以及解析
,对于4xx/5xx,我还返回分派(nextroraction(data))
和拒绝
。它最终运行得很好,只需要几行代码。找不到有关是否应传递额外参数的任何文档。认为我可能根本不需要参与行动?定义一个fetchSecretSauce
方法,该方法在action creator之外进行提取。谢谢@crysfel的回答。一个问题。什么是后期加载,后期成功?它是一个action creator函数,还是一个具有类型和动作的对象。有没有可能添加一个动作的例子?只是动作名称:const POSTS\u LOAD='myapp/POST\u L'代码>您将在减速器上收到此信息。基于此名称,您可以对数据或状态执行任何操作。我添加了一个减速机示例。抱歉,忽略前面的。我的代码中有一个愚蠢的错误。非常感谢你的帮助。我在这里学到了很多东西,现在也感觉到了创建自己的redux中间件的速度。
export function reducer(state = {}, action) {
switch(action.type) {
case POST_SUCCESS: // <-- Action name
return {
...state,
posts: action.json.posts, // <-- Getting the data from the action
}
default:
return state;
}
}