了解Redux和State

时间:2017-10-08 03:22:45

标签: javascript reactjs redux react-redux

我参加了两个课程,树屋和一个关于udemy,关于react / redux,当我想到自己“嘿,你得到了这个,让我们做一些练习”我遇到了一些我看不出的巨大错误诊断。

我在这里尝试做的事听起来非常简单,并且在普通的JavaScript中它可以工作。我的状态是一个空对象state = {},当我的动作被调用时,它会在状态noteName内创建一个数组。因此,在一天结束时,州应该看起来像state = { noteName: [ ...state.noteName, action.payload]}

当我console.log(this.props.inputvalue)时,它将返回input元素中的任何内容。我以为我理解了对象,因为控制台日志应该返回数组noteName而不是实际值,对吗?

代码

操作/ index.js

export const INPUT_VALUE = 'INPUT_VALUE';

export function addNoteAction(text) {
  return {
    type: INPUT_VALUE,
    payload: text
  }
}

减速器/ reducer_inputvalue.js

import { INPUT_VALUE } from '../actions';

// state is initialized as an empty object here
export default function(state = {}, action) {
  switch (action.type) {
    case INPUT_VALUE:
      state.noteName = [];
      // this SHOULD create an array that concats action.payload with
      // whatever is already inside of state.name
      return state.noteName = [...state.noteName, action.payload];
    default:
      return state;
  }
}

noteitems.js

import React, { Component } from 'react';
import { connect } from 'react-redux';

class NoteItems extends Component {
  render() {
    return (
      <ul>
        { 
          this.props.inputvalue.noteName 
          ?
          this.props.inputvalue.noteName.map((note, index) => {
            // this should iterate through noteName but returns undefined
            return <li key={index}>{note}</li>;
          }) 
          :
          <li>Nothing here</li>
        }
      </ul>
    );
  }
}

function mapStateToProps(state) {
  return {
    inputvalue: state.inputvalue
  }
}

export default connect(mapStateToProps)(NoteItems);

2 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为每次调度操作int时,您都会重置INPUT_VALUE。 redux的主要原则是不修改状态,而是根据当前创建一个新状态。在你的情况下:

noteName

答案 1 :(得分:0)

您在切换案例的第一行覆盖state.noteName

switch (action.type) {
  case INPUT_VALUE:
    state.noteName = [];

在Redux中,重点是永远不会覆盖某个值,但要返回一个可能是全新值的新值,可能是一个基于旧值的值(但仍然是一个新值...不覆盖旧的,或者它可能会返回旧值(完全未修改)。

const counterReducer = (counter, action) => {
  const options = {
    [COUNTER_INCREMENT]: (counter, action) =>
      ({ value: counter.value + 1 }),
    [COUNTER_DECREMENT]: (counter, action) =>
      ({ value: counter.value - 1 }),
    [COUNTER_RESET]: (counter, action) =>
      ({ value: 0 })
  };
  const strategy = options[action.type];

  return strategy ? strategy(counter, action) : counter;
};

在该示例中,我没有修改counter上的值。所有内容都被视为只读