【问题标题】:Redux Reducer that simply returns an action's value and not a state?Redux Reducer 只返回一个动作的值而不是一个状态?
【发布时间】:2017-08-11 09:36:58
【问题描述】:

我有一个 Container、一个 actionsCreator 和一个 reducer。在下面的代码中,是什么使 Reducer 返回 action.text 而不是更新的状态对象?我认为减速器必须始终返回状态。

HelloWorldContainer.jsx

 import { connect } from 'react-redux';
 import HelloWorld from '../components/HelloWorld';
 import * as actionCreators from '../actions/helloWorldActionCreators';

 const mapStateToProps = (state) => ({ name: state.name });

 export default connect(mapStateToProps, actionCreators)(HelloWorld);

helloWorldActionCreators.jsx

 import { HELLO_WORLD_NAME_UPDATE } from '../constants/helloWorldConstants';

 export const updateName = (text) => ({   
   type: HELLO_WORLD_NAME_UPDATE,  
   text, 
 });

helloWorldReducer.jsx

 import { combineReducers } from 'redux';
 import { HELLO_WORLD_NAME_UPDATE } from '../constants/helloWorldConstants';

 const name = (state = '', action) => {
   switch (action.type) {
     case HELLO_WORLD_NAME_UPDATE:
       return action.text
     default:
       return state;
   }
 };

 const mainReducer = combineReducers({ name });

 export default mainReducer;

(代码来源:React on Rails)。

【问题讨论】:

    标签: reactjs redux react-redux react-on-rails


    【解决方案1】:

    我认为减速器必须总是返回状态。

    没有。 Reducer 必须始终返回数据。此外,您不应该返回状态,而是一个新对象(或其他数据类型)。

    因此,在您的情况下,reducer 每次调度 HELLO_WORLD_NAME_UPDATE 操作时都会返回一个新字符串(或任何数据类型为 text)。它不关心状态中已经存在的内容并返回一个新的文本字符串。

    【讨论】:

    • reducer 确实返回了一个新状态
    • 当然,reducer 返回的数据将成为存储的一部分,称为状态(数据)。我试图向问题作者解释的是,他认为他有义务从减速器返回状态对象。
    【解决方案2】:

    name 只是状态的一部分。而action.text更新状态。

    combineReducers({ name })之后,状态树如下:

    {
      name: '..'
    }
    

    此外,redux 并没有限制你只能使用对象作为你的状态。如果你直接将name 传递给createStore() 而没有combineReducers,你的整个状态将变成一个纯字符串。

    【讨论】:

    • 好的,所以我的下一个问题是,在helloWorldReducer.jsx 内部,作为参数传递给reducer 的state 不是应用程序的整个状态,但是 property 的 Redux 存储中的状态,其值是传递给 combineReducers 的对象中的 reducer - 但前提是那是传递给 createStore 函数的内容。我这样想对吗?
    • 是的。此外,Redux 非常灵活,完全不会限制你。任何接收 oldState + action 并返回新状态的函数都是 reducer。您可以编写一个处理所有事情的巨型减速器;或几个微型减速器并任意组合它们。
    • state 并不总是一个对象。任何字符串、数字或数组.. 一切都可以是状态
    猜你喜欢
    • 2020-11-10
    • 2019-04-01
    • 2020-07-07
    • 2019-11-22
    • 2021-04-01
    • 2016-09-27
    • 2018-11-15
    • 2017-04-02
    • 2021-04-28
    相关资源
    最近更新 更多