Muhammad Muaz
Muhammad Muaz

Reputation: 227

Unable to setState with props in class component

I have a class component which can be viewed by 2 screens and 1 screen is passing props and 1 is not. so i want to set default value "" 0r empty if there are no props and if there are props then value should be based on props. but i'm unable to do so. Any help will be appreciated.. flow is like this.. main screen==> rating(without props so state should be empty)==>search screen==>rating(with props. state should get value from state)

class Rating extends Component {
constructor() {
super();
const propItem = this.props?.route.params.item;
this.state = {
brand : propItem != undefined ? propItem.brand : "",

i have tried componentDidMount but it cause infinite loop so does if i uset it in render method

Upvotes: 0

Views: 157

Answers (3)

Alok Singh
Alok Singh

Reputation: 181

class Rating extends Component {
constructor(props) {
    super(props);

this.state = {
  brand : this.props?.route.params.item != undefined ? this.props?.route.params.item.brand : ""
}}
render() {
<div></div>
}}

you can try like it, make sure your are passing item from previous screen in this.props.navigation

Upvotes: 0

Satel
Satel

Reputation: 187

You need to pass the pros for constructor and super function.

class Rating extends Component {
  constructor(props) {
    super(props);
    const propItem = this.props?.route.params.item;

    this.state = {
      brand : propItem != undefined ? propItem.brand : ""
    }
  }

  render() {
    <div></div>
  }
}

Upvotes: 0

Yu Mao
Yu Mao

Reputation: 101

Try getDerivedStateFromProps

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

Upvotes: 1

Related Questions