【发布时间】:2021-08-18 19:48:35
【问题描述】:
我正在开发一个基于 React 和 Django 的后端项目。而且我收到此错误“对象作为 React 子对象无效(找到:带有键 {bookId、title、image、price、countInStock、qty} 的对象)。如果您打算渲染一组子对象,请改用数组。”
这是我的钩子:
function CartScreen({ match, location }) {
const bookId = match.params.id
const qty = location.search ? Number(location.search.split("=")[1]) : ""
const dispatch = useDispatch()
const cart = useSelector((state) => state.cart)
useEffect(() => {
if (bookId) {
dispatch(addToCart(bookId, qty))
}
}, [dispatch, bookId, qty])
return <div>Shopping cart</div>
}
这是动作创建者:
export const addToCart = (id, qty) => async (dispatch, getState) => {
const { data } = await axios.get(`/api/books/${id}`)
dispatch({
type: "CART_ADD_ITEM",
payload: {
bookId: data.id,
title: data.title,
image: data.image,
price: data.price,
countInStock: data.count_in_stock,
qty,
},
})
localStorage.setItem("cartItems", JSON.stringify(getState().cart.cartItems))
}
这是减速器:
export const cartReducer = (state = { cartItems: [] }, action) => {
switch (action.type) {
case "CART_ADD_ITEM":
const item = action.payload
let index = -1
state.cartItems.forEach((x, i) => {
if (x.bookId === item.bookId) index = i
})
if (index !== -1) {
state.cartItems[index] = item
return {
...state,
cartItems: state.cartItems,
}
} else
return {
...state,
cartItems: [...state.cartItems, item],
}
}
}
但令人惊讶的是,尽管该操作已创建并且 cartItems 正在进入状态,但操作创建者仍显示错误。但是之后出现了这个错误。
N.B.- 状态已更新,但 cartItems 未存储在 localStorage 中。
Action creator showing error cartItems loaded in redux store
以前从 CartScreen 挂钩中,我返回了更多代码行,但由于它似乎对错误没有任何影响,所以我出于测试目的将其删除。
我还看到了与此相关的其他查询,但似乎没有任何效果,因为实际上我不明白错误是从哪里产生的。 我是新手,所以请原谅我的任何愚蠢错误。
感谢您对此问题的任何帮助或建议:)
【问题讨论】:
标签: javascript reactjs redux