React state with calculated fields

后端 未结 6 1847
半阙折子戏
半阙折子戏 2021-02-13 18:24

I have a react component, which has properties and state. Some fields of state contain input data (uplifted from input control), but there is also fields in the state that must

6条回答
  •  我在风中等你
    2021-02-13 18:50

    Do not include redundant information in your state.

    A simplified example is having firstName and lastName in your state. If we want to display the full name in your render method, you would simply do:

    render() {
        return {`${this.state.firstName} ${this.state.lastName}`}
    
    }
    

    I like this example because it's easy to see that adding a fullName in our state, that just holds ${this.state.firstName} ${this.state.lastName} is unnecessary. We do string concatenation every time our component renders, and we're okay with that because it's a cheap operation.

    In your example, your calculation is cheap so you should do it in the render method as well.

提交回复
热议问题