首页 > 解决方案 > 我的基本 redux 商店没有 console.log 状态更改

问题描述

我目前正在研究 NetNin​​ja 的 redux 播放列表。不幸的是,我遇到了一个我正在努力克服的问题。我开始着手向我的 reducer 发送多个操作,现在我无法再让我的 store.subscribe 方法执行更新状态的 console.log。我花了大约 40 分钟试图解决这个问题,非常感谢任何帮助。

这是我正在使用的 CodePen 的直接链接:https ://codepen.io/davidreke/pen/MWKWYdd

如果您愿意,这是我在 Stack Overflow 中的代码

const {
  createStore
} = Redux;

console.log('the basics work')

const initState = {
  todos: [],
  posts: []
}
// 2. add a spread operator to include all the state in a reducer
function myReducer(state = initState, action) {
  if (action.type == 'ADD_TODO') {
    return {
      ...state,
      todos: [...state.todos, action.todo]
    }

    if (action.type == 'ADD_POST') {
      return {
        ...state,
        posts: [...state.posts, action.post]
      }
    }
  }

  const store = createStore(myReducer)

  // 1. add a subscription to the store and then preview it in the console.log

  store.subscribe(() => {
    console.log('state updated');
    console.log(store.getState())
  })


  store.dispatch({
    type: 'ADD_TODO',
    todo: 'sleep some more'
  })

  store.dispatch({
    type: 'ADD_TODO',
    todo: 'prepare node.js'
  })


  store.dispatch({
    type: 'ADD_POST',
    post: 'Hello world!'
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>

标签: redux

解决方案


我的减速器函数中缺少一个大括号,它破坏了代码。

function myreducer(state = initState, action){
  if (action.type =='ADD_TODO') {
    return {
      ...state,
      todos: [...state.todos, action.todo]
    } 
  }

  if (action.type =='ADD_POST') {
    return {
      ...state,
      posts: [...state.posts, action.post]
    }
  }
}

推荐阅读