Redux 减速器的副作用

dam*_*amd 6 javascript side-effects reactjs redux

Redux 减速器应该没有副作用。但是,如果一个动作应该触发在浏览器中下载一个文件,其中内容是基于商店的状态呢?这当然应该算作副作用吗?像下面这样的东西会很好还是我应该寻找替代方法?

case 'SAVE_GRID': {
  const { json } = state
  fileDownload(json, 'data.json', 'application/json')
  return state
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*yon 6

除非您有非常复杂的状态转换,否则实际fileDownload应该发生在动作创建器中,而不是在减速器中。减速器应该负责合并/减少状态,仅此而已。

行动:

export const saveGrid = (json) => {
   return (dispatch) => {  
       fileDownload(json, 'data.json', 'application/json')
           .then(() => {
              dispatch({ type: 'SAVE_GRID', json });
           });
   }
}
Run Code Online (Sandbox Code Playgroud)

减速器:

case 'SAVE_GRID': {
    return {
        ...state,
        json: action.json
    }
}
Run Code Online (Sandbox Code Playgroud)