【问题标题】:Redux Keep showing undefine stateRedux 一直显示未定义状态
【发布时间】:2019-04-07 14:58:28
【问题描述】:

我是 React 和 Redux 的新手。 虽然我在互联网上找到了很多资源,但它仍然无法正常工作。 希望有人可以帮助我。

我想用点击触发一个组件 Q1:我跟踪初始状态并发现它工作正常,但它在组件中显示未定义 Q2:如何继续订阅状态? (比如用 console.log 打印出来)


代码:index.js

import .....

const store = createStore(rootReducer)
console.log(store.getState())
render(
  <Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)

App.js

import ToggleSidebar from '../containers/ToogleSidebar'
const App = () => (
<div>
     <ToggleSidebar/>
</div>
)
export default App

减少.js

const sidebar = (state={open:false}, action) => {
    switch (action.type) {
      case 'TOGGLE_SIDEBAR':
      return {
          ...state,
          open : !state.open
      }
      default:
      return state
    }
  }

  export default sidebar

合并

import { combineReducers } from 'redux'

import sidebar from './sidebar'
export default combineReducers({
  sidebar
})

行动

export const toggleSideBar = () => ({
  type: 'TOGGLE_SIDEBAR',

})

容器

import { connect } from 'react-redux'
import { toggleSideBar } from '../actions'
import Sidebar from '../components/Sidebar'

const mapStateToProps = (state) => ({
   open: '...'+state.open+'...'
})

const mapDispatchToProps = (dispatch) => ({
    toggleSideBar: () => dispatch(toggleSideBar())
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Sidebar)

组件

const  Sidebar = ({open,toggleSideBar}) =>  (

        <div>
          <button onClick={toggleSideBar}>
            {open} 
          </button>
        </div>
)
  export default Sidebar

当我在 index.js 中使用日志时,我看到了“打开”的初始状态 但组件中的按钮显示未定义 请帮助我,非常感谢

【问题讨论】:

  • 是 ToggleSidebar 与将侧边栏连接到减速器后在容器中导出的组件相同
  • 是容器,当我命名它们时我感到很困惑,但人们似乎不需要使用更具体的名称......所以我想我应该尝试......现在我想我应该把它命名为 SidebarContainer ...

标签: reactjs redux components containers state


【解决方案1】:

您在 Container 中的 mapStateToProps 函数应该使用 state.sidebar.open 而不是 state.open。当您调用combineReducers({ sidebar }) 时,您正在创建一个类似{ sidebar: { open: false } } 的状态结构。请参阅combineReducers here 上的文档。

【讨论】:

  • 非常感谢帮我弄清楚!我也可以知道如何继续订阅商店吗?我知道如何在 index.js 中没有 Provider 的情况下做到这一点我是否应该将 App.js 变成一个状态组件,以便它会在 componentwillmount 中调用它?请给我一些建议
  • 不客气!我很抱歉,但我没有按照你的要求进行操作。 connect 函数为您订阅商店。任何时候更新状态,任何连接的(容器)组件都将使用mapStateToProps 从状态中检索新值。您不需要在componentWillMount 或其他任何地方进行任何手动订阅。如果这不能回答您的问题,我建议发布另一个 StackOverflow 问题并提供一些代码示例来展示您要解决的问题。
  • 我只是想像 store 一样打印出来,但现在我想我应该直接打印状态,谢谢你澄清我的困惑! :)
猜你喜欢
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 2016-12-22
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 2021-12-16
相关资源
最近更新 更多