一个 React-Redux Action 更新多个 Reducer [英] a React-Redux Action Update Multiple Reducers

查看:53
本文介绍了一个 React-Redux Action 更新多个 Reducer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个 Action 如何更新多个不同的 Reducer?我该如何实现?

How an Action update multiple different Reducers? How can i implement like this?

更新:

这是我在 ./actions/sync.js 中的操作.此操作连接到外部 API 并定期从同步组件调用.

this is my action in ./actions/sync.js. this action connected to an external API and call from Sync Component, periodically.

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})
    }
}

和./reducers/sync.js

and ./reducers/sync.js

const initialState = [];

export default (state = initialState, action) => {
    switch(action.type) {
        case 'SYNC_FETCH':
            return action.response;

        default:
            return state;
    }
}

我没有出错,但数据没有更新.我的代码有什么问题?

i got not error, but data not update. what is problem in my code?

推荐答案

每个 action 都被分派给所有的 reducer,reducer 可以决定他们是否希望使用 action 来更新某些东西

each action is being dispatched to all the reducers, the reducers may decide whether they wish to use the action to update something or not

你想要的是

const updateAll = params => {
    return {type: 'UPDATE_PARAMS', payload: params}
}

然后在不同的减速器中使用它

and then use it in different reducers like

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
   }
}

这篇关于一个 React-Redux Action 更新多个 Reducer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆