【问题标题】:How to put a default value in a React component with redux?如何在使用 redux 的 React 组件中设置默认值?
【发布时间】:2019-03-11 19:54:46
【问题描述】:

我问自己是否有办法使用 props 初始化 React 组件,并自动让 Redux 意识到这一点以更新其应用程序状态?

我做了一个反例:

import React from 'react';
import {createStore} from "redux"
import {Provider} from "react-redux"

import Counter from "./Counter"
import countReducer from "./ducks.js"

const store = createStore(countReducer)

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <div className="App">
          <Counter />
        </div>
      </Provider>
    );
  }
}

export default App;

Counter.js

import React from 'react';
import {connect} from "react-redux"
import {increment, decrement, reset} from "./ducks"

const Counter = ({count, decrement, increment, reset}) => (
    <div>
      <h1>Counter</h1>
      <button onClick={decrement}>-</button>
      <span style={{ margin: "0 10px" }}>{count}</span>
      <button onClick={increment}>+</button>
      <div>
        <button onClick={reset}>Reset</button>
      </div>
    </div>
  );

const mapStateToProps = ({count}) => ({
  count
})

const mapDispatchToProps = {
  decrement,
  increment,
  reset
}

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

ducks.js

// action creators
export const increment = () => ({
  type: "INC"
})

export const decrement = () => ({
  type: "DEC"
})

export const reset = () => ({
  type: "RESET"
})

// reducers
export default function countReducer(state = { count: 0 }, action) {

  switch (action.type) {
    case "INC":
      return { count: state.count + 1 }
    case "DEC":
      return { count: state.count - 1 }
    case "RESET":
      return state.defaultCount ? {
          count: state.defaultCount
        } : {
          count: 0
        }
    default:
      return state
  }
}

它按预期工作:我们可以在值 0 上递增、递减或重置。

但是如果我们想重置另一个值呢?

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <div className="App">
          <Counter defaultValue={10}/>
        </div>
      </Provider>
    );
  }
}

我想到的另一个问题是如何管理具有不同计数器的 2 个计数器,同时仍然让 redux 处理整个状态?

很可能我想以错误的方式做某事,所以即使你有最佳实践,我也会很感激。

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    我问自己是否有办法初始化一个 React 组件 props,并自动让 Redux 意识到这一点以更新其 应用状态?

    我对此规范的解决方案是使用componentDidMount() 生命周期挂钩。我们可能会有这样的事情:

    componentDidMount(){
       if(this.props.defaultValue){
          this.props.initCounter(this.props.defaultValue);
       }
    }
    ...
    const mapDispatchToProps = dispatch({
       ...
       initCounter: defaultValue  => dispatch({type: 'INIT_COUNTER', payload: {defaultValue}})
       ...
    })
    

    我们需要在 reducer 中处理这个动作,实现与您所做的非常相似。

    我想到的另一个问题是如何管理 2 个计数器 使用不同的计数器,同时仍然让 redux 处理整个状态?

    那么,我们的状态将是一个 counter 对象数组,如下所示:

    const reducer = (state = [ { id: 1, value:77 }, { id: 2, value: 88} ], action) => {
          switch (action.type):
               case 'INCREMENT':
                   return state.map(c => {
                         if(action.payload.id === c.id) return {...c, value: c.value + 1};
                         return c;
                   });
               case 'DECREMENT':
                   return state.map(c => {
                         if(action.payload.id === c.id) return {...c, value: c.value - 1};
                         return c;
                   })
               ...
               default:
                   return state;
    };
    

    我们使用id 来指定需要更新的计数器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 2018-07-26
      • 2019-01-08
      • 2016-12-11
      • 2018-08-09
      • 2019-08-02
      相关资源
      最近更新 更多