一个动作如何更新多个不同的减速器?我该如何实施?
更新:
这是我在./actions/sync.js中的操作。此操作会定期连接到外部API并从同步组件进行调用。
export function syncFetch(response) {
return {
type: 'SYNC_FETCH',
response
}
}
export function syncFetchData(url) {
return (dispatch) => {
fetch(url)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
})
.then((response) => response.json())
.then((sync) => updateAll(sync))
.catch(() => console.log('error'));
};
}
const updateAll = (params) => {
return dispatch => {
dispatch({type: 'SYNC_FETCH', payload: params})
}
}
Run Code Online (Sandbox Code Playgroud)
和./reducers/sync.js
const initialState = [];
export default (state = initialState, action) => {
switch(action.type) {
case 'SYNC_FETCH':
return action.response;
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
我没有错误,但是数据没有更新。我的代码有什么问题?
每个动作都被分派给所有的减速器,减速器可以决定是否希望使用该动作来更新某些东西
你想要的是
const updateAll = params => {
return {type: 'UPDATE_PARAMS', payload: params}
}
Run Code Online (Sandbox Code Playgroud)
然后在不同的减速器中使用
const newReducer = (state= initialState, action) => {
switch(action.type) {
case 'UPDATE_PARAMS': return {
...state,
// do some things here
}
...
default: return state;
}
}
const userReducer = (state= initialState, action) => {
switch(action.type) {
case 'UPDATE_PARAMS': return {
...state,
// do some things here
}
...
default: return state
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的一种方法可能是触发批处理操作。所以你可以有三个不同的动作,每个减速器一个,然后有一个主要动作来处理所有这三个动作(或者只是在第一个动作下添加两个动作)。这可以通过使用 thunk(thunk 中间件)来完成。做类似的事情,假设它们是异步的:
const updateAllNewsStuff = newsParam => {
return dispatch => {
dispatch(newsAction(newsParam))
dispatch(userAction(newsParam))
dispatch(notifyAction(newsParam))
}
}
Run Code Online (Sandbox Code Playgroud)
您可能还可以查看此插件来触发批处理操作:https : //github.com/tshelburne/redux-batched-actions
从react-redux 7.1,您可以利用batchAPI 在一次重新渲染时分派所有操作。从文档中,您可以执行以下操作:
import { batch } from 'react-redux'
function myThunk() {
return (dispatch, getState) => {
// should only result in one combined re-render, not two
batch(() => {
dispatch(newsAction(newsParam))
dispatch(userAction(newsParam))
dispatch(notifyAction(newsParam))
})
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2095 次 |
| 最近记录: |