dispatch(fetchPosts()) 给出空状态

dispatch(fetchPosts()) give empty state

提问人:b2ok 提问时间:5/4/2023 最后编辑:b2ok 更新时间:5/6/2023 访问量:74

问:

这里没问题,response.data 是数组:

export const fetchPosts = createAsyncThunk('posts/fetchPosts', async () => {
  const response = await axios.get('https://640114a00a2a1afebee5c77d.mockapi.io/post1')
  console.log(response)
return response.data
})

这里不是,状态为空:

useEffect(() => {
    console.log(postStatus)
    if (postStatus === 'idle') {
      dispatch(fetchPosts())
    }
  }, [postStatus, dispatch])

我尝试在 React Redux 应用程序中使用 thunk 和 Mock 服务器上的数据。

帖子列表:.js:

import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { selectAllPosts, fetchPosts } from './postsSlice'
import { Spinner } from '../../components/Spinner'

const PostExcerpt = ({ post }) => {
  return (
    <article className="post-excerpt" key={post.id}>
      <h3>{post.title}</h3>
      <p className="post-content">{post.content.substring(0, 100)} 
   </p>
    </article>
      )
    }

export const PostsList = () => {
  const dispatch = useDispatch()
  const posts = useSelector(selectAllPosts)
  console.log(posts)
  const postStatus = useSelector((state) => state.posts.status)
  const error = useSelector((state) => state.posts.error)

console.log(posts)

  useEffect(() => {
    console.log(postStatus)
    if (postStatus === 'idle') {
      dispatch(fetchPosts())
    }
  }, [postStatus, dispatch])

  let content

  if (postStatus === 'loading') {
    content = <Spinner text="Loading..." />
  } else if (postStatus === 'succeeded') {
    content = posts.map(post => (
      <PostExcerpt key={post.id} post={post} />
    ))
  } else if (postStatus === 'failed') {
    content = <div>{error}</div>
  }

  console.log(content)
return (
  <section>
    <h2>Posts</h2>
    {content}   
  </section>
)
}

帖子切片.js:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

const initialState = {
  posts: [],
  status: 'idle',
  error: null,
}

export const fetchPosts = createAsyncThunk('posts/fetchPosts', async () 
=> {
  const response = await 
axios.get('https://640114a00a2a1afebee5c77d.mockapi.io/post1')
  //console.log(response)
  console.log('fetchPosts response:', response)
  return response.data
})

console.log(fetchPosts)

export const addNewPost = createAsyncThunk(
  'posts/addNewPost',
  // The payload creator receives the partial `{title, content, user}` 
 object
  async (initialPost) => {
    // We send the initial data to the fake API server
    const response = await 
axios.post('https://640114a00a2a1afebee5c77d.mockapi.io/post1',  
initialPost)
    // The response includes the complete post object, including unique 
 ID
    return response.data
  }
)

const postsSlice = createSlice({
  name: 'posts',
  initialState,
  reducers: {  
    extraReducers(builder) {
      builder
        .addCase(fetchPosts.pending, (state) => {
          state.status = 'loading'
        })
        .addCase(fetchPosts.fulfilled, (state, action) => {
          state.status = 'succeeded'
          // Add any fetched posts to the array
          state.posts = state.posts.concat(action.payload)
        })
        .addCase(fetchPosts.rejected, (state, action) => {
          state.status = 'failed'
          state.error = action.error.message
        })
        .addCase(addNewPost.fulfilled, (state, action) => {
          // We can directly add the new post object to our posts array
          state.posts.push(action.payload)
        })
      }
    }
  })

export default postsSlice.reducer

export const selectAllPosts = state => state.posts.posts

console.log(selectAllPosts)

export const selectPostById = (state, postId) =>
  state.posts.posts.find(post => post.id === postId)

我一直在学习这个 https://redux.js.org/tutorials/essentials/part-5-async-logic 有本地服务器,我使用模拟服务器端点。

存储 .js:

import { configureStore } from '@reduxjs/toolkit';
import postsReducer from '../features/posts/postsSlice'

export const store = configureStore({
  reducer: {
    posts: postsReducer
  }
})
console.log(store.getState())
reactjs redux 服务器 模拟 thunk

评论

1赞 Drew Reese 5/5/2023
我在该端点上看到服务器 500 错误。你能编辑这篇文章以澄清你所指的具体状态是空的吗?参见最小可重复示例。有趣的是,您的原始终结点确实返回数据。
0赞 b2ok 5/5/2023
@Drew Reese 我编辑了端点。现在就试试吧。
1赞 Drew Reese 5/5/2023
因此,端点正在工作并返回数据。这之后有什么问题?
0赞 b2ok 5/5/2023
1. 在帖子切片控制台.log('fetchPosts response:', response)没问题,帖子数组 2.after dispatch(fetchPosts()) in PostsList nothing dispatch to state
1赞 Drew Reese 5/5/2023
什么是“PostsList”?你希望被派往什么州?你能把代码添加到你的最小可重现的例子中吗?postsSlice

答:

0赞 b2ok 5/6/2023 #1

在postsSlice中.js在单词reducer和冒号之后有一个开放的大括号,我没有关闭并在其后加一个逗号。

这是正确的 reducers: { },