Redux:访问当前状态-最佳做法?

时间:2018-07-24 11:56:56

标签: javascript reactjs react-native react-redux flux

关于Redux,这是我不了解的地方。我有一个通过项目的应用程序。您可以转到上一个项目和下一个项目。据我了解,您不应在操作中访问当前状态。

关于我的应用程序,我在redux状态下有一个数组,其中存放着我所有商品的ID:["3123123123","1231414151","15315415", etc.],在状态中我的状态是存放着currently selected item(或者更好,保留该项目的 id )。现在,当用户单击nextItem时,我需要获得下一项。我的(未完成的)操作如下所示:

export function nextItem(currentId) {

  //my idea:
  //take the currentId, look where in the array it is, and get the position
  //increment that position
  //get the id of the next item in the array (at position: position+1)
  //update state

  return {
    type: SET_CURRENT_ITEM,
    payload: item
  }
}

类似的情况适用于先前的Item动作创建者。但是,我不知如何在不访问当前状态的情况下实现此操作创建者?理想情况将在哪里发生,如何发生?

3 个答案:

答案 0 :(得分:2)

我建议您分派以下操作:

{
    type: INCREMENT_CURRENT_ITEM
}

您可以直接从任何已连接的组件中调度此消息:

dispatch({ type: INCREMENT_CURRENT_ITEM })

或者,如果您更喜欢使用动作创建者,也可以:

dispatch(incrementItem()) // incrementItem() returns the action above

在化简器中,您可以访问当前状态,在这里您可以增加项目索引,而不必在数组中搜索当前值。

答案 1 :(得分:1)

我可能会添加一个组件,负责通过应用程序增加商品ID

Edit k0847p7k7

import React from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { nextItem } from "../redux/actions";

const ItemNav = ({ nextItem, items, item }) => {

  function setNextItem() {
    let currentItemID = items.indexOf(item) + 1;
    if (currentItemID >= items.length - 1) currentItemID = 0;
    nextItem(items[currentItemID]);
  }

  return (
    <ul>
      <li>previous item</li>
      <li onClick={setNextItem}>next item</li>
    </ul>
  );
};

const mapStateToProps = state => ({
  items: state.items,
  item: state.item
});

const mapDispatchToProps = dispatch => bindActionCreators({ nextItem },dispatch);

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

答案 2 :(得分:0)

The reducer is a pure function。生产者必须收到 相同类型的参数,生产者必须计算新的 状态版本并返回。没什么好奇怪的没有副作用。没有 调用第三方API。无变化(变异)。只有 状态的新版本的计算。

  

纯功能-从根本上讲,任何不具备的功能   更改输入不依赖于外部状态(数据库,DOM   或全局变量),并为相同的输入返回相同的结果   数据作为纯函数。

此外,如果这些值在另一个reducer中,该怎么办?

动作创建者-也是纯函数,为了进行计算,我们必须 从商店接收数据

组件-在组件不良做法中使用业务逻辑

保留中间件,为了不产生很多中间件,最好 使用 redux-thunk

此外,还有一个类似问题的链接:     Redux: Reducer needs state of other Reducer?

以及第一个找到的实现此情况的项目的链接:     https://github.com/rwieruch/favesound-redux/blob/master/src/actions/player/index.js

相关问题