How to use setState in if Else

Asked

Viewed 264 times

0

I need help using . setState() in if Else after render(), if possible...

render() {
    const propsDesign = this.props.design, 
          propsIcon = this.props.icon,
          propsText = this.props.text,
          propsDescription = this.props.description;


    var object = {
        design: propsDesign,
        icon: propsIcon,
        text: propsText,
        description: propsDescription
    };

    if(propsDesign === 'normal' || propsDesign === 'narrator' || propsDesign === 'error' ) {
        console.log("Design true");
        this.setState({design: propsDesign});
    } else {
        console.log("Design false");
        this.setState({design: 'error'});
    }

    return <Container design=??? />;
}
  • This is Stackoverflow in English, please translate your question.

  • I didn’t even realize it was in Portuguese, but it’s translated

  • No problem, just to keep order ^^

1 answer

3


Not use setState inside render(), this can cause infinite loops, because the method render is called when the state is updated, so when you put the setState within the render, it will update the state and call the render, update the state again and call the render and so on, the method render must be pure.

If you need to change the state use functions before the render() and lifecycles of React.

And yes it is possible to use the if with the setState, the way you did. If you want to initialize these variables as soon as the page is assembled, use the componentDidMount(). Example:

componentDidMount() {
    const propsDesign = this.props.design, 
          propsIcon = this.props.icon,
          propsText = this.props.text,
          propsDescription = this.props.description;


    var object = {
        design: propsDesign,
        icon: propsIcon,
        text: propsText,
        description: propsDescription
    };

    if(propsDesign === 'normal' || propsDesign === 'narrator' || propsDesign === 'error' ) {
        console.log("Design true");
        this.setState({design: propsDesign});
    } else {
        console.log("Design false");
        this.setState({design: 'error'});
    }
}

render() {
    return <Container design={this.state.design} />;
}

Ref Docs React Lifecycles: https://pt-br.reactjs.org/docs/state-and-lifecycle.html

Ref on setState() in the render(): https://blog.logrocket.com/an-imperative-guide-to-setstate-in-react-b837ceaf8304/

  • Thanks! Solved my problem and made me understand a little more about the state.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.