Reducer以不可变的方式导致Uncaught Error

时间:2017-12-10 22:46:01

标签: javascript reactjs redux

我在尝试设置状态时做了一些严重的错误。我目前只有一个键值对{view: ''}作为应用程序状态。试图设置'部分'作为一个值导致该单词被每个字母分开(从redux chrome扩展名复制):

{view: {'0': 's','1': 'e','2': 'c','3': 't','4': 'i','5': 'o','6': 'n','7': 's', view: 'sections'}

以下错误:

  

未捕获错误:对象无效作为React子对象(找到:具有键{0,1,2,3,4,5,6,7,view}的对象)。如果您要渲染子集合,请改用数组。

正在使用的减速器:

export default function reducer(state={}, action) {
  switch (action.type) {
    case "SET_VIEW": {
      return {...state, view: action.payload}
    }
  }
  return state
}

以下减速机有效,但我希望能够设置上面的状态,我可以指定键/键:

export default function view(state={}, action) {
  switch (action.type) {
    case 'SET_VIEW':
      return action.payload
    default:
    return state
  }
}

此代码是否足以了解出现问题的地方?如有必要,我很乐意分享更多代码。抱歉没有更好的头衔,但我不知道问题的主题是什么。

更新

申请的初始状态:

const store = createStore(rootReducer, {view: 'sections'})

组件代码:

import React, { Component } from 'react'
import { connect } from 'react-redux'
import {setView} from '../actions/viewActions';

class App extends Component {
  render() {
    return (
      <div>
        <div onClick={() => this.props.setView('settings')}>SETTINGS</div>
        <div onClick={() => this.props.setView('sections')}>SECTIONS</div>
        {this.props.view}
      </div>
    )
  }
}

const mapStateToProps = (state) => ({
  view: state.view
})
const mapDispatchToProps = dispatch => {
  return {
    setView: (value) => {
        dispatch(setView(value));
    }
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App)

文件viewActions.js中的操作:

export const setView = (view) => ({
  type: 'SET_VIEW',
  payload: view
})

1 个答案:

答案 0 :(得分:0)

仍然不知道为什么你的代码不起作用。我创建了简单的demo,它重复了你的代码,并且工作正常。希望,这将是有益的。