Javascript Redux-如何通过ID从存储中获取元素 [英] Javascript Redux - how to get an element from store by id

查看:93
本文介绍了Javascript Redux-如何通过ID从存储中获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几周里,我一直在尝试学习React和Redux. 现在我遇到了一个问题,我没有找到正确的答案.

For the past weeks I've been trying to learn React and Redux. Now I have met a problem thay I haven't found a right answer to.

假设我在React中有一个页面,该页面从链接中获取道具.

Suppose I have a page in React that gets props from the link.

const id = this.props.params.id;

现在在此页面上,我想显示具有此ID的STORE中的对象.

Now on this page, I'd like to display an object from STORE with this ID.

 const initialState = [
      {
        title: 'Goal',
        author: 'admin',
        id: 0
      },
      {
        title: 'Goal vol2',
        author: 'admin',
        id: 1
      }
    ]

我的问题是: 从STORE查询对象的函数应该在页面文件中,在render方法之前,还是应该使用动作创建者并将函数包括在reducers中. 我注意到,reduce似乎只包含对商店没有影响的动作,而我的只是查询商店.

My question is: should the function to query the the object from the STORE be in the page file, before the render method, or should I use action creators and include the function in reducers. I've noticed that the reduceres seem to contain only actions that have an impoact on store, but mine just queries the store.

谢谢.

推荐答案

将组件连接到redux时,可以使用mapStateToProps函数查询商店:

You could use the mapStateToProps function to query the store when you connect the component to redux:

import React from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';

const Foo = ({ item }) => <div>{JSON.stringify(item)}</div>;

const mapStateToProps = (state, ownProps) => ({
  item: _.find(state, 'id', ownProps.params.id)
});

export default connect(mapStateToProps)(Foo);

(此示例使用lodash-_)

(This example uses lodash - _)

mapStateToProps函数接受整个redux状态和组件的prop,然后您可以决定将什么作为prop发送给组件.因此,鉴于我们所有的商品,请查找ID与我们的网址匹配的商品.

The mapStateToProps function takes in the whole redux state and your component's props, and from that you can decide what to send as props to your component. So given all of our items, look for the one with the id matching our URL.

https://github.com/rackt/react-redux/blob/master/docs/api.md#arguments

这篇关于Javascript Redux-如何通过ID从存储中获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆