【问题标题】:I can't use state.filter in Redux reducer我不能在 Redux reducer 中使用 state.filter
【发布时间】:2016-04-24 13:47:13
【问题描述】:

所以我正在使用 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')
)
;

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

提前感谢您的所有建议或解决方案。

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    在您的case 'DELETE_HOSTNAME' 中,您正在调用state.filter。此时您的状态将是 Object 而不是数组。

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 2021-02-26
    • 2018-02-07
    • 1970-01-01
    • 2020-04-24
    • 2016-06-21
    • 2023-03-22
    • 2018-04-22
    相关资源
    最近更新 更多