redux 返回undefined

txu3uszq  于 2023-11-19  发布在  其他
关注(0)|答案(1)|浏览(120)

我是Redux的新手,我正在学习一些教程,我们正在构建的应用程序是创建一些帖子。
我所面临的是,当我使用usebooks时,这个钩子返回undefined,即使状态已经完成并且有效负载存在。
组件Posts.js

import React from "react";
import { useSelector } from "react-redux/";

import Post from "./Post/Post";

const Posts = () => {
    const posts  = useSelector((state) => state.posts);

    console.log("POSTS FROM STATE: ", posts);

    return (
        <>
            <h1>POSTS</h1>
            <Post />
            <Post />
        </>
    );
}

export default Posts;

字符串

store.js

import { configureStore } from "@reduxjs/toolkit";
import fetchReducer from "./fetchSlice";

export default configureStore({
    reducer: {
        fetch: fetchReducer,
    },
});

fetchSlice.js

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

export const getPostsAsync = createAsyncThunk(
    'posts/getPostsAsync',
    async () => {
        try {
            const resp = await fetch('http://localhost:5000/posts');
            console.log("response: ", resp);
            if (resp.ok) {
                const posts = await resp.json();
                console.log("resp json: ", posts);
                return { posts };
            }
        } catch(error) {
            console.log(error);
        };
    }
);

export const fetchSlice = createSlice({
    name: 'posts',
    initialState: [],
    reducers: {
        fetchAll: (state, action) => {
            return action.payload.posts;
        },
        create: (state, action) => {
            return
        },
    },
    extraReducers: (builder) => {
        console.log("extra builder");
        builder
            .addCase(getPostsAsync.pending, (state) => {
                console.log("Request pending");
            })
            .addCase(getPostsAsync.rejected, (state) => {
                console.log("Request rejected");
            })
            .addCase(getPostsAsync.fulfilled, (state, action) => {
                console.log("Fulfilled, reducer payload: ", action.payload.posts);
                return action.payload.posts;
            })
    }
});

export const { fetchAll, create } = fetchSlice.actions;

export default fetchSlice.reducer;

App.js

import React, { useEffect } from "react";
import { Container, AppBar, Typography, Grow, Grid, ThemeProvider } from "@mui/material";
import { useDispatch } from "react-redux";

import Posts from "./components/Posts/Posts";
import Form from "./components/Form/Form";
import memories from "./images/memories.png";

import { getPostsAsync } from "./redux/fetchSlice";
import { theme } from "./styles";

const App = () => {
    
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(getPostsAsync());
    }, [dispatch]);

    return (
        <Container maxwidth="lg">
            <ThemeProvider theme={theme}>
                <AppBar sx={theme.appBar} position="static" color="inherit">
                    <Typography sx={theme.heading} variant="h2" align="center">Memories</Typography>
                    <img sx={theme.image} src={memories} alt="memories" height="60" />
                </AppBar>
                <Grow>
                    <Container>
                        <Grid container justify="space-between" alignItems="stretch" spacing={3}>
                            <Grid item xs={12} sm={7}>
                                <Posts />
                            </Grid>
                            <Grid item xs={12} sm={4}>
                                <Form />
                            </Grid>
                        </Grid>
                    </Container>
                </Grow>
            </ThemeProvider>
        </Container>
    );
}

export default App;


我可以在redux商店中看到有效负载存在:

但是,当我尝试控制台记录我用于useLog的参数时,它返回undefined:

我错过了什么?提前感谢。

tvokkenx

tvokkenx1#

在你的store.js文件中,你已经将你的reducer切片命名为fetch

export default configureStore({
    reducer: {
        fetch: fetchReducer,
    },
});

字符串
但是,在您的Posts.js文件中,您试图从state获取帖子:

const posts  = useSelector((state) => state.posts);


这与您在商店中指定的名称不一致。
更改Posts.js中的useSelector以匹配您在store.js中定义的内容:

const posts = useSelector((state) => state.fetch);


这应该解决你的问题。

相关问题