我不能在Redux reducer中使用state.filter

Mat*_*ias 3 javascript reactjs redux react-redux

所以我使用的是React-Redux,在我的reducer中我想从我的状态中删除一个主机名.所以从环顾四周我发现state.filter是实现这一目标的好方法.但是,这不起作用,我在控制台中不断收到错误.

index.js

import "babel-polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import thunkMiddleware  from 'redux-thunk';
import createLogger from 'redux-logger'
import { HostnameAppContainer } from './components/HostnameApp';
import {createStore, applyMiddleware} from 'redux';
import hostnameApp from './reducer'
import {fetchHostnames} from './action_creators'

const loggerMiddleware = createLogger()

const store = createStore(
    hostnameApp,
    applyMiddleware(
        thunkMiddleware, // lets us dispatch() functions
        loggerMiddleware // neat middleware that logs actions
    )
)

store.dispatch(fetchHostnames())

ReactDOM.render(
    <Provider store={store}>
        <HostnameAppContainer />
    </Provider>,
document.getElementById('app')
)
;
Run Code Online (Sandbox Code Playgroud)

reducer.js

export default function(state = {hostnames:[]}, action) {
    switch (action.type) {
        case 'FETCH_HOSTNAMES':
            return Object.assign({}, state, {
                hostnames: action.hostnames
            })
        case 'DELETE_HOSTNAME':
            return state.filter(hostname =>
                hostname.id !== action.hostnameId
            )
        case 'ADDED_HOSTNAME':
            return Object.assign({}, state, {
                hostnames: [
                    ...state.hostnames,
                    action.object
                ]
            })
    }
    return state;
}
Run Code Online (Sandbox Code Playgroud)

错误

谢谢您提前获取所有建议或解决方案.

Cla*_*kie 6

case 'DELETE_HOSTNAME'你的呼唤中state.filter.此时你的状态将是一个Object而不是一个数组.

你可能想要做这样的事情:

case 'DELETE_HOSTNAME':
  return { hostnames: state.hostnames.filter(hostname =>
     hostname.id !== action.hostnameId
  )}
Run Code Online (Sandbox Code Playgroud)