简体   繁体   English

在React-Redux应用程序中放置实用程序功能的位置?

[英]Where to put utility functions in a React-Redux application?

In a React-Redux application, I've got a state like this: 在React-Redux应用程序中,我有一个这样的状态:

state = {
    items: [
        { id: 1, first_name: "John", last_name: "Smith", country: "us" },
        { id: 2, first_name: "Jinping", last_name: "Xi", country: "cn" },
    ]
}

which I render using a React component. 我使用React组件渲染。

Now I need a function that gives me the "full name" of a person. 现在我需要一个能给我一个人“全名”的功能。 So it's not just "first_name + last_name" but it depends on the country (for example, it would be "last_name + first_name" in China), so there's some relatively complex logic, which I would like to wrap in a function usable from any React component. 所以它不仅仅是“first_name + last_name”,而是取决于国家(例如,它在中国将是“last_name + first_name”),所以有一些相对复杂的逻辑,我想把它包装在一个可以从任何地方使用的函数中反应组件。

In OOP I would create a Person::getFullName() method that would give me this information. 在OOP中,我将创建一个Person::getFullName()方法,它将为我提供此信息。 However the state object is a "dumb" one where sub-objects don't have any specialized methods. 然而, state对象是一个“哑”的state ,其中子对象没有任何专门的方法。

So what is the recommended way to manage this in React-Redux in general? 那么一般来说,在React-Redux中管理它的推荐方法是什么? All I can think of is create a global function such as user_getFullName(user) which would take a user and return the full name, but that's not very elegant. 我能想到的只是创建一个全局函数,例如user_getFullName(user) ,它将占用用户并返回全名,但这不是很优雅。 Any suggestion? 有什么建议吗?

I follow the approach of creating libraries for cases like this in my applications, and so far this works pretty well for me. 我遵循在我的应用程序中为这样的情况创建库的方法,到目前为止,这对我来说非常有效。

In this case, I would create a new module , eg {ComponentRoot}/lib/user.js which exports a function getFullName(user) or possibly getFullName(firstName, lastName, country) , depending the circumstances. 在这种情况下,我将创建一个新模块 ,例如{ComponentRoot}/lib/user.js ,它根据情况导出函数getFullName(user)或可能的getFullName(firstName, lastName, country)

Now it is just a matter of importing the module where you require the functionality , no global functions needed: 现在只需要导入需要功能的模块 ,不需要全局功能:

import React from 'react'
import {getFullName} from '../lib/user'

const Title = ({user}) =>
    <div>
        {getFullName(user)}
    </div>

We place our library folder on the same level as the components folder etc., but whatever works best for you should do. 我们将库文件夹放在与组件文件夹等相同的级别上,但是哪种方法最适合您应该这样做。

First of all, Redux has no opinion on the file structure of your application . 首先, Redux对您的应用程序的文件结构没有意见

Some famous boilerplate projects put the code into an utils/ folder: 一些着名的样板项目将代码放入utils/文件夹:

Sample folder structure: 示例文件夹结构:

  • src/ SRC /
    • components/ 组件/
      • ... ...
    • reducers/ 减速机/
      • ... ...
    • utils/ utils的/
      • ... ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM