[英]I can't use state.filter in Redux reducer
所以我正在使用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;
}
謝謝您提前獲取所有建議或解決方案。
在你的case 'DELETE_HOSTNAME'
你正在調用state.filter
。 此時您的狀態將是Object
而不是數組。
你可能想要做這樣的事情:
case 'DELETE_HOSTNAME':
return { hostnames: state.hostnames.filter(hostname =>
hostname.id !== action.hostnameId
)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.