问题
Say I have React component that renders a set of buttons,I store the information for the buttons in an object, with a label and a method to run when they are attached.
The buttons do not need to react to any changes, and will never change themselves.
Is it a bad practice to store the information for these buttons in the state? These are the current solutions I have come up with so far.
1. Storing Buttons in State
class Header extends Component {
constructor() {
super();
this.state = {
buttons: [
{
label: 'Save',
method: this.save
},
{
label: 'Edit',
method: this.edit
}
]
}
}
// Class Methods
// ...
// End of Class Methods
render() {
<ButtonGroup buttons={this.state.buttons} />
}
}
2. Storing Buttons outside of React's State
class Header extends Component {
constructor() {
super();
this.buttons = [
{
label: 'Save',
method: this.save
},
{
label: 'Edit',
method: this.edit
}
];
}
// Class Methods
// ...
// End of Class Methods
render() {
<ButtonGroup buttons={this.buttons} />
}
}
3. Using a Stateless Functional Component (applicable only if no class methods are needed and no other state is used)
function save() {
...
}
function edit() {
...
}
const buttons = [
{
label: 'Save',
method: save
},
{
label: 'Edit',
method: edit
}
];
const Header = () => (<ButtonGroup buttons={buttons} />);
What the question really boils down to is:
- Is it a bad practice to store data in the state that will not change, and remain constant?
- Will using state for constants effect performance?
- Is there a reason to store data that won't change within the state, If I do have state elsewhere, is it easier to just use the state for everything?
回答1:
Quick answers to your questions:
Is it a bad practice to store data in the state that will not change, and remain constant?
Somewhat, yes. The state is meant to store the current "state" of your UI. If a specific UI component never changes it doesn't really make sense to talk about "states", because there is only one.
Will using state for constants effect performance?
No.
If there a reason to store data that won't change within the state, If I do have state elsewhere, is it easier to just use the state for everything?
There isn't really, but even if it was considered a valid practice, I would argue that you are sacrificing readability and structure in your code because you wouldn't be distinguishing between the static and dynamic stuff in your UI.
Based on the snippets provided, I would strongly suggest either (2)
or (3)
. I would consider both of these good practices depending on where you want to store the data (within or outside your component) and if flexibility is important.
来源:https://stackoverflow.com/questions/48261439/is-it-a-bad-practice-to-use-state-in-a-react-component-if-the-data-will-not-chan