I
I
Ivan Pavlenko2018-10-03 16:54:32
React
Ivan Pavlenko, 2018-10-03 16:54:32

How to force a component update when setState() is called?

What a story, I use the following construction to display nested pages.

class Screen extends Componen {
  constructor(props) { 
    super(props)

    this.state = {
      screen: undefined
    }
  }

  render() {
    return this.state.screen ? this.state.screen : <div className="content">
    </div>
  }
}

Further, by calling , you can change the page, it is conveniently redrawn, and everything would be fine if not for one small but. If screen was previously set to the same component, then it is not redrawn when a new component appears to be assigned. Found a way out in the form of the following crutch:
this.setState({screen: <MyMyComponenr/>})
this.setState({screen: undefined}, ()=>{
    this.setState({
      screen: <ShowScreen />
    })
  })
}}

But something tells me I'm wrong about something.
Is there any way to tell react that this is a new component and that it needs to be re-rendered.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
davidnum95, 2018-10-04
@davidnum95

this.setState({ screen: <Random key={Math.random()} /> });

Do not thank.

M
Mikhail Osher, 2018-10-03
@miraage

What's happening. React understands that the same component needs to be rendered, so it doesn't re-render it. If you add the componentDidUpdate method, you will see that it is being called - React reuses the existing component instance.
The problem is that this is a so-so approach in React. In order, in my opinion, to write this example more concisely in the React way, we need to slightly correct the responsibility of each component.
https://codesandbox.io/s/2vl0801r6r

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question