简体   繁体   中英

What is the best practice in react.js to use a constants value in a component

If a child component requires a globally settable constant, such as the available booking time, for example: SESSION_ RANGE = [9, 17] .

I need to parse it into a function ( sessionCreator ) first. What the child component really accepts is an array of objects (sessionData).

Then I need to use this in the parents component:
const sessionData = sessionCreator(SESSION_RANGE);

However, there are several options that I can choose: 1. Inside the render() of the parent component. 2. Create a getSessionData function inside the class, and then use the code above inside the getSessionData function.

Given this use case, what is the best practice to use for the parents component?

const sessionData = sessionCreator(SESSION_RANGE);
import { SESSION_RANGE } from '../../constants/setting';
import { sessionCreator } from '../../utils/function';
//option3

class Parent extends Component {
  //option2

  render(){
    // option 1
    return (
      <Child dataSource={sessionData} />
    )

if this is constant and will never change, then i would put it outside of the component because when the component rerender - the constant will be recreated for no reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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