redux 应用程序逻辑在哪里更好?

Where is it better to make the redux app logic?

我有一个 react-redux 应用程序,其中存在某个 action-creator(函数获取任何标题以过滤列表objects):

export const filterTests = (title) => dispatch => {
    axios.get(`/api/tests/?title=${title}`)
        .then(res => {
            dispatch({
                type: GET_TESTS,
                payload: res.data
            });
            dispatch({
                type: FILTER_TESTS,
                payload: { title }
            });
        })
        .catch(err => console.log(err))
}

还有一个reducer:

export default function (state = initialState, action) {
    switch (action.type) {
        case GET_TESTS:
            return {
                ...state,
                tests: action.payload,
            };
        case FILTER_TESTS:
            return {
                ...state,
                tests: state.tests.filter((test) => test.title.includes(action.payload.title)),
            };
        default:
            return state;
    }
}

它有效,但我认为最好将过滤逻辑移到其他地方(特别是如果我想使操作复杂化):

tests: state.tests.filter((test) => test.title.toLowerCase().includes(action.payload.title.toLowerCase()))

这个逻辑转移到哪里比较好?

根据 Redux 文档,

reducer 中绝对不应该做的事情:

  • 改变它的参数;
  • 执行 API 调用和路由转换等副作用;
  • 调用non-pure函数,例如Date.now() 或 Math.random().

只要你的功能逻辑是reducer就是正确的地方。

如果您担心代码行数,可以将逻辑移动到函数名称如 filterByTitle(...)Utils.js 文件中。然后在 reducer 中导入该函数并按如下方式使用它

case FILTER_TESTS:
  return {
    ...state,
    tests: filterByTitle(state.tests, action.payload.title),
  };