[英]How can I set another state to pass data to from the initial state in a react class component
[英]How can I set a component initial state with another state before render?
我有一個包含數據的 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" },
]
}
這是顯示卡片的父類。 單擊卡片時,它將導航到另一個組件,即 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>
)
}
}
在 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 })
}
在 DataForm 中,我希望類型字段的默認值為“hetero”或“homo”。 但是它顯示錯誤為:
無法讀取未定義的屬性類型。
如何獲取類型字段中的默認值?
提前致謝。
您的組件可能無權訪問this.tempData.type 。 請提供您的組件的完整代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.