伙计们,我的React Redux设置有问题, 我正在使用redux工具包,
在搜索时,我看到了一些解决方案,但是由于异步调用正在执行,因此它们不符合我的需求 在UseEffect函数之外进行。 为什么当我切换到另一个页面时我什至没有再次打个电话
我的代码:
import React, { useState,useEffect, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { query, currToy,CurrToys } from './toySlice';
export function ToyApp() {
const toysFromDb=useSelector(CurrToys)
const[localStateToys,setToys]=useState([])
const dispatch = useDispatch();
const mountedRef = useRef(true)
useEffect(() => {
dispatch(query()).then(data=>{
setToys(toysFromDb)
})
}, [localStateToys])
return (
<div>
{localStateToys.map(toy=>{
return(<article key={toy._id}>
<li>{toy.name}</li>
</article>)
})}
</div>
)
}
切片:
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
const baseUrl = '/api/toys';
export const query = createAsyncThunk('loadToys', () =>
axios.get(baseUrl)
.then(ok => ok.data)
.catch(err => err),
);
export const toySlice = createSlice({
name: 'toysServices',
initialState: {
toys:[],
currToy:null
},
reducers: {
test: (state, action) => {
console.log('In Test')
},
},
extraReducers: {
[query.fulfilled]: (state, action) => {
state.toys = action.payload
}
}
});
export const { test } = toySlice.actions;
export const CurrToys = state => state.toyReducer.toys;
export const currToy = state => state.toyReducer.currToy;
export default toySlice.reducer;