简单的Redux Counter组件实现

时间:2016-11-23 15:26:33

标签: javascript reactjs redux react-redux

我正在尝试使用简单的Redux实现计数器组件,使用store创建了createStore并使用了store.dispatch

完整代码:



/*==================================================
This is only to format the code, I have used this editor, 
you can scroll down for the fiddle having error.
==================================================*/


 const createStore = Redux.createStore;

 const counter = (state = {
     counter: 0
 }, action) => {
     console.log('counter', state)
     switch (action.type) {
         case 'INCREMENT':
             return state.counter + 1;
         case 'DECREMENT':
             return state.counter - 1;
         default:
             return state;
     }
 }

 const store = createStore(counter);

 let Counter = React.createClass({
     getInitialState() {
         return store.getState()
     },

     incrementCounter() {
         store.dispatch({
             type: 'INCREMENT'
         });
     },
     decrementCounter() {
         store.dispatch({
             type: 'DECREMENT'
         });
     },

     render() {

         console.log('NEW STATE:', store.getState(), this.state)
         return (
              <div>
                <p>{this.state.counter}</p>
                <div>
                <button onClick={this.incrementCounter}>+</button>
                <button onClick={this.decrementCounter}>-</button>
                </div>
              </div>
      ) 
     }

 })

 ReactDOM.render( < Counter / > , document.getElementById('container'))
         
   
&#13;
&#13;
&#13;  

DEMO JSFIDDLE

我的问题:当我点击incrementCounterdecrementCounter函数

时,我无法在渲染块中获得更新存储值

2 个答案:

答案 0 :(得分:1)

您有几个问题

  1. 您需要 订阅 进行状态更改,这很重要,因为您的组件不了解新状态
  2. stateObject,您必须从counter Object返回,在您的示例中,您返回Number中的INCREMENT和{{} 1}}
  3. DECREMENT
    const createStore = Redux.createStore;
    
    const counter = (state = {
      counter: 0
    }, action) => {
      switch (action.type) {
        case 'INCREMENT':
          return Object.assign({}, state, { counter: state.counter + 1 });
        case 'DECREMENT':
          return Object.assign({}, state, { counter: state.counter - 1 });
        default:
          return state;
      }
    }
    
    const store = createStore(counter);
    
    let Counter = React.createClass({
      incrementCounter() {
        store.dispatch({ type: 'INCREMENT' });
      },
      
      decrementCounter() {
        store.dispatch({ type: 'DECREMENT' });
      },
    
      render() {
        return <div>
          <p>{ this.props.value }</p>
          <div>
            <button onClick={this.incrementCounter}>+</button>
           	<button onClick={this.decrementCounter}>-</button>
          </div>
        </div> 
      }
    })
    
    const render = () => {
      ReactDOM.render(
        // get updated state value, and pass it to component
        <Counter value={ store.getState().counter } />, 
        document.getElementById('container')
      )
    };
    
    store.subscribe(render);
    render();

    注意:对于<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.6.0/redux.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="container"></div>Reactreact-redux)提供了名为Redux的组件,您不需要使用{{1}然而,在引擎逻辑中类似于我的例子

    <强>更新

    Provider
    store.subscribe

答案 1 :(得分:1)

你的主要问题是:

const counter = (state = {
     counter: 0
 }, action) => {
     console.log('counter', state)
     switch (action.type) {
         case 'INCREMENT':
             return state.counter + 1;
         case 'DECREMENT':
             return state.counter - 1;
         default:
             return state;
     }
 }

特别是这一行:

         case 'INCREMENT':
             return state.counter + 1;
         case 'DECREMENT':
             return state.counter - 1;
你回来了什么?一个号码!但是你的状态形状是一个对象{counter: Number}

所以你必须返回一个像这样的新对象:

         case 'INCREMENT':
             return {counter: state.counter + 1}
         case 'DECREMENT':
             return {counter: state.counter - 1}

以上更改应该修复它。 要在reducer中更灵活,您应该将新对象分配给现有状态,如下所示:

         case 'INCREMENT':
             return {
                ...state,
                counter: state.counter + 1
             }
         case 'DECREMENT':
             return {
                ...state,
                counter: state.counter - 1
             }