简体   繁体   中英

How can I set a component initial state with another state before render?

I am having a json file with data

  {
    data = [ {name: 'abc", label: "ABC",type: "hetero", path:"/assets/data/source1.jpg" }, 
             {name: 'pqr", label: "PQR",type: "homo", path:"/assets/data/source2.jpg" },
             {name: 'xyz", label: "XYZ",type: "hetero", path:"/assets/data/source3.jpg" },
             ]
  }

This is the Parent class which is displaying the cards. On click of cards, It will navigate to another component which is DataForm.

class MainDataCard extends React.Component{

 onClickForm = card => {
      const {action} = this.props;  // action value can be add/update. Currently action = "add"
      this.props.history.push(`/user/${action}/${card.label}`);
    };
  render() {
                {data.map((card, index) => {
    return (
      <Card
        key={index}
        className="cardStyle"
        onClick={() => {
          this.onClickForm(card);
        }}
      >
        <CardContent className="cardContent">
          <Grid container>
            <Grid item md={12}>
              <img src={card.path} alt="card" />
            </Grid>
            <Grid item md={12}>
              <Typography color="textSecondary" gutterBottom>
                {card.name}
              </Typography>
            </Grid>
          </Grid>
        </CardContent>
      </Card>
         )
              } 
        }

In DataForm component, I am having a state for the form fields as:

        state = {
           dataForm: {
                  name: "",
                  type: this.tempData.type,
                  userName: "",
                  password: ""
                    },
                  tempData: {}
                  }

    componentDidiMount(){
          const {label} = this.props.match.params;
          let temp ={};
          {data.map((card) => {
              if(data.label === label) {
                temp =data;
                 }
           })};
             this.setState({ tempData : temp })

        }

In DataForm, I want type field to have a default value as "hetero" or "homo". But there its showing an error as:

CANNOT READ PROPERTY TYPE OF UNDEFINED.

How can I get the default value in type field??

Thanks in advance.

Your component probably do not have access to this.tempData.type . Please provide full code of your components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM