[英]How can I set a component initial state with another state before render?
I am having a json file with data我有一个包含数据的 json 文件
{
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.
单击卡片时,它将导航到另一个组件,即 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:在 DataForm 组件中,我将表单字段的状态设置为:
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".在 DataForm 中,我希望类型字段的默认值为“hetero”或“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 .您的组件可能无权访问this.tempData.type 。 Please provide full code of your components.
请提供您的组件的完整代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.