What is Lifting State Up?
What is Lifting State Up?
Lifting state up is a common pattern in React and React Native development used to share state between multiple components. This technique involves moving the state from child components to their closest common ancestor (parent component). By doing so, the parent component becomes the "single source of truth" for the shared state, and it can pass the state down to its children via props. This ensures that all components that depend on the shared state are in sync and can update the state consistently.
Consider a scenario where you have two input components that need to reflect the same data. Instead of each input maintaining its own local state, you lift the state up to their common parent component. Here’s a simple example:
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = { sharedState: '' };
this.handleStateChange = this.handleStateChange.bind(this);
}
handleStateChange(newState) {
this.setState({ sharedState: newState });
}
render() {
return (
<div>
<ChildComponent1
sharedState={this.state.sharedState}
onStateChange={this.handleStateChange}
/>
<ChildComponent2
sharedState={this.state.sharedState}
onStateChange={this.handleStateChange}
/>
</div>
);
}
}
const ChildComponent1 = ({ sharedState, onStateChange }) => (
<input
type="text"
value={sharedState}
onChange={(e) => onStateChange(e.target.value)}
/>
);
const ChildComponent2 = ({ sharedState, onStateChange }) => (
<input
type="text"
value={sharedState}
onChange={(e) => onStateChange(e.target.value)}
/>
);
In this example, ParentComponent
holds the shared state and passes it down to ChildComponent1
and ChildComponent2
via props. Both child components can read and update the shared state through the onStateChange
handler provided by the parent.
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào