这是负责获取数据和更新列表的代码:
import {createSlice} from "@reduxjs/toolkit";
import axios from "axios";
const initialState = {
log: []
}
let page = 1;
const cartSlice = createSlice({
name: 'cart',
initialState: initialState,
reducers: {
fetching: (state, payload) => {
state.log = axios.get(`http://localhost:5000/fetch/?${page = payload.payload}`)
// console.log(state)
}
}
})
export const {fetching} = cartSlice.actions;
export default cartSlice.reducer;
这是主页:
import React, {useEffect} from "react";
import {useDispatch, useSelector} from "react-redux";
import {fetching} from "../features/cardSlice";
import Cards from "./Cards";
export default function HomePage(){
const dispatch = useDispatch();
const {itemsList} = useSelector((store) => store.card)
console.log(itemsList)
const {pageNumber} = useSelector((store) => store.page);
useEffect(()=>{
dispatch(fetching(1)); **// This is where i call dispatch to update the state and get the data**
})
function cardMapper(items) {
return(
<Cards
name = {items.name}
key = {items.id}
cuisine={items.cuisine}
address={items.address}
/>
)
}
return(
<div>
{/*{itemsList.map(cardMapper)}*/}
</div>
)
}
当我在本地主机上运行这个时,我无法获得数据,console.log(itemList)显示未定义,并且调度(抓取(1))被无限次调用。
Uncaught Error: Maximum update depth exceeded。当组件在componentWillUpdate或componentdiduupdate中重复调用setState时,就会发生这种情况。React限制嵌套更新的数量以防止无限循环。
我不明白为什么我得到一个无限循环,也为什么我没有得到数据。
我修改了你的代码为了防止使用useEffect时的无限循环,你应该把[]作为依赖项对于useSelector,变量不应该被{}括起来。请参阅下面修改后的代码。如我所见,它应该是cart不是卡
试试这段代码
export default function HomePage(){
const dispatch = useDispatch();
const itemsList = useSelector((store) => store.cart)
console.log(itemsList)
const {pageNumber} = useSelector((store) => store.page);
useEffect(()=>{
dispatch(fetching(1)); **// This is where i call dispatch to update the state and get the data**
},[])
function cardMapper(items) {
return(
<Cards
name = {items.name}
key = {items.id}
cuisine={items.cuisine}
address={items.address}
/>
)
}
return(
<div>
{/*{itemsList.map(cardMapper)}*/}
</div>
)
}
也适用于减速机添加一个返回
fetching: async (state, payload) => {
const newState = await axios.get(`http://localhost:5000/fetch/?${page = payload.payload}`)
return newState;
}
//这应该结束无限循环
useEffect(()=>{调度(抓取(1));//这是我调用调度更新状态和获取数据}, [])
您需要添加依赖项作为空数组去掉黄色弯弯曲曲的线你需要在依赖性数组中添加分派。但是,反应以确保分派依赖项永远不会更改你不负责重新渲染你的组件。
useEffect(()=>{
dispatch(fetching(1))
},[dispatch])