React Redux 在减速器中分配箭头函数警告

React Redux Assign Arrow Function Warning in reducers

有人能告诉我为什么我的 React 应用程序会收到此警告吗?

src/reducers/posts.js Line 3:1: Assign arrow function to a variable before exporting as module default

import { FETCH_ALL, CREATE, UPDATE, DELETE } from '../constants/actionTypes';

export default (posts = [], action) => {
    switch (action.type) {
        case FETCH_ALL:
            return action.payload;
        case UPDATE:
            return posts.map((post) => post._id === action.payload._id ? action.payload : post);
        case CREATE:
            return [ ...posts, action.payload];
        case DELETE:
            return posts.filter((post) => post._id !== action.payload);
        default:
            return posts;
    }
}

向您的函数添加变量:

export default const variable = (posts = [], action) => {
    switch (action.type) {
        case FETCH_ALL:
            return action.payload;
        case UPDATE:
            return posts.map((post) => post._id === action.payload._id ? action.payload : post);
        case CREATE:
            return [ ...posts, action.payload];
        case DELETE:
            return posts.filter((post) => post._id !== action.payload);
        default:
            return posts;
    }
}

JavaScript 必须知道你在导出什么

您不能同时导出默认值声明一个变量。 试试这个:

const variable = (posts = [], action) => {
    switch (action.type) {
        case FETCH_ALL:
            return action.payload;
        case UPDATE:
            return posts.map((post) => post._id === action.payload._id ? action.payload : post);
        case CREATE:
            return [ ...posts, action.payload];
        case DELETE:
            return posts.filter((post) => post._id !== action.payload);
        default:
            return posts;
    }
}

export default variable

或使用传统命名函数导出默认值:

export default function variable(posts = [], action) {
    switch (action.type) {
        case FETCH_ALL:
            return action.payload;
        case UPDATE:
            return posts.map((post) => post._id === action.payload._id ? action.payload : post);
        case CREATE:
            return [ ...posts, action.payload];
        case DELETE:
            return posts.filter((post) => post._id !== action.payload);
        default:
            return posts;
    }
}