【问题标题】:State object structure in react-redux applicationreact-redux 应用程序中的状态对象结构
【发布时间】:2020-07-12 15:07:42
【问题描述】:

我正在使用 React 和 Redux 创建一个简单的博客,主要用于学习这两个库。一切正常,我唯一的问题是关于状态对象在应用程序中的结构方式。当我转到 Redux Toolkit 时,我看到了这个:

Redux Toolkit screenshot

在我有 一个 post 对象和另一个 post 对象的状态下。我的问题是:我在哪里以这种方式定义了状态(在 post 对象中使用 post 对象)? 以下是此应用程序的内容:

MainPost.js

import React, { useEffect } from 'react'
import { connect, useDispatch } from 'react-redux'
import { getPostListAction } from '../store/actions/getPostListAction'

export const MainPost = () => {
   const dispatch = useDispatch()
   useEffect(() => {
      dispatch(getPostListAction())
   })

   return (
      <div>App</div>
   )
}

const mapStateToProps = state => {
   return {
      post: state.post
   }
}

export default connect(mapStateToProps)(MainPost)

store.js

import { createStore, applyMiddleware, compose } from 'redux'
import rootReducer from './reducers/rootReducer'
import { devToolsEnhancer } from 'redux-devtools-extension'
import thunk from 'redux-thunk'
import { api } from './middleware/api'

const store = createStore(
   rootReducer,
   compose(
      devToolsEnhancer(),
      applyMiddleware(thunk),
   )
)

export default store

postListReducer.js

const initialState = {
   post: ''
}

export default function getPostListReducer(state = initialState, action) {
   if(action.type === 'getPostList') {
      return {
         ...state,
         post: action.payload
      }
   } else {
      return state
   }
}

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    第一个post(在state之后)是postListReducer的命名空间

    以下是使用combineReducer 创建rootReducer 的方法:

    const rootReducer = combineReducers({
      post: postListReducer, 
      other: otherReducer
    })
    

    to select data from the store,你做到了:

    const mapStateToProps = state => {
       return {
          post: state.post.post // the first "post" (after "state") is namespace of postListReducer
       }
    }
    
    

    或者如果你不想写state.post.post,你可以把你的postListReducer改成直接保存“post”数据:

    const initialPost = ''
    
    export default function getPostListReducer(state = initialPost, action) {
       if(action.type === 'getPostList') {
          return action.payload
       } else {
          return state
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      相关资源
      最近更新 更多