Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - Where to put utility functions in a React-Redux application?

In a React-Redux application, I've got a state like this:

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.

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.

In OOP I would create a Person::getFullName() method that would give me this information. However the state object is a "dumb" one where sub-objects don't have any specialized methods.

So what is the recommended way to manage this in React-Redux in general? 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. Any suggestion?

question from:https://stackoverflow.com/questions/40870777/where-to-put-utility-functions-in-a-react-redux-application

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, e.g. {ComponentRoot}/lib/user.js which exports a function getFullName(user) or possibly getFullName(firstName, lastName, country), depending the circumstances.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...