我有这个:
const initialState = {
pages: [],
page: null,
loading: true,
error: {}
};
然后我有这个:
import {
GET_PAGES,
PAGE_ERROR,
DELETE_PAGE,
ADD_PAGE,
} from '../actions/types';
const initialState = {
pages: [],
page: null,
loading: true,
error: {}
};
export default function (state = initialState, action) {
const { type, payload } = action;
switch (type) {
case GET_PAGES:
return {
...state,
page: null,
pages: payload,
loading: false
};
case ADD_PAGE:
return {
...state,
pages: [payload, ...state.pages],
loading: false
};
case DELETE_PAGE:
return {
...state,
pages: state.pages.filter(page => page._id !== payload),
loading: false
};
case PAGE_ERROR:
return {
...state,
error: payload,
loading: false
};
default:
return state;
}
}
每次我从数据库中删除一个条目时,都会显示一条错误消息,指出“ state.pages.filter不是函数”。我已经为此苦苦挣扎了很长时间。任何帮助将不胜感激! 这就是我的组件中的内容:
const Pages = ({ getPosts, page: { pages, loading }, deletePost }) => {
useEffect(() => {
getPosts();
}, [getPosts]);
return (
<Fragment>
{loading ? (
<Spinner />
) : (
<section className="mb-3">
<div className="container-fluid">
<h1 className="border-bottom-dark pb-3 mb-3">Pages</h1>
{pages && pages.pageOfItems ? (
<div className="row">
<div className="col-lg-12">
<div className="table-responsive">
<table className="table table-bordered" id="dataTable" width="100%" cellSpacing="0">
<thead>
<tr>
<th></th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{pages.pageOfItems.map(post => (
<tr key={post._id}>
<td></td>
<td className="btn-group">
<Link to={`/admin/pages/view/${post._id}`} className="btn btn-sm btn-dark"><i className="far fa-eye" /></Link>
<Link to={`/admin/pages/update/${post._id}`} className="btn btn-sm btn-warning"><i className="fas fa-edit" /></Link>
<button onClick={() => deletePost(post._id)} type="button" className="btn btn-danger btn-sm"><i className="fas fa-trash-alt" /></button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
) : (
<div className="nothingfound">
<div className="alert alert-danger">No pages found</div>
</div>
)}
</div>
</section>
)}
</Fragment>
)
};
Pages.propTypes = {
getPosts: propTypes.func.isRequired,
deletePost: propTypes.func.isRequired,
page: propTypes.object.isRequired,
};
const mapStateToProps = state => ({
page: state.page,
});
export default connect(
mapStateToProps,
{ getPosts, deletePost }
)(Pages);
答案 0 :(得分:0)
正如其他人所建议的那样,您应该console.log您的state.posts:
case DELETE_PAGE:
console.log(state.pages); // here
return {
...state,
pages: state.pages.filter(page => page._id !== payload),
loading: false
};
也许您的GET_PAGES操作正在返回一个非数组作为有效载荷:
case GET_PAGES:
return {
...state,
page: null,
pages: payload, // Is the payload an array?
loading: false
};
处理redux时,我还建议在分派每个动作之后注销您的状态,以更好地了解您的状态(例如可以使用redux-logger)。