Câu hỏi phỏng vấn React Native
Câu hỏi

What is Lifting State Up?

Câu trả lời

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.

Example of Lifting State Up

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.

Benefits of Lifting State Up

  1. Consistency: Ensures that all components reflect the same state, avoiding inconsistencies....
middle

middle

Gợi ý câu hỏi phỏng vấn

expert

How is InteractionManager important?

senior

What are some advantages of Component Driven Development?

middle

How do you re-render a FlatList?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào