[英]How to render object that pass through props in ReactJS?
我正在嘗試渲染來自道具的數據(對象)。 但是,我收到以下錯誤:
Uncaught TypeError: Cannot convert undefined or null to object
Some how, I do not know why the data or object is null although the state of the data
is updated during componentDidMount()
. 你能幫我為什么數據是 null 嗎?
請看class A
看看數據是怎么消耗的
class A extends React.Component {
state = {
data: null
};
componentDidMount() {
this.data = this.props.location.state.data;
this.setState({ data: this.props.location.state.data });
}
render() {
return (
<div>
{Object.keys(this.data).map((key, index) => (
<p key={index}> value is {this.data[key]}</p>
))}
hello
</div>
);
}
}
A.propTypes = {
data: PropTypes.object,
location: PropTypes.object
};
export default A;
假設this.data
包含以下格式的數據
{
id: 1,
userName: "ABDXY",
date: "01/12/2020",
time: "21:00"
}
this.data
未定義。 您可以使用this.state.data
訪問 state 中設置的數據
請確保this.props.location.state.data
不是 null
class A extends React.Component {
state = {
data: {}
};
componentDidMount() {
// this.data = this.props.location.state.data; => not required.
this.setState({
data: this.props.location.state.data
});
}
render() {
return ( <
div > {
Object.keys(this.state.data).map((key, index) => ( <
p key = {
index
} > value is {
this.state.data[key]
} < /p>
))
}
hello <
/div>
);
}
}
從 state 而不是this.data
獲取數據,因為當this.data
更新時它不會觸發渲染。 也使用{}
作為默認值
class A extends React.Component {
state = {
data: {}
};
componentDidMount() {
const data = {
id: 1,
userName: "ABDXY",
date: "01/12/2020",
time: "21:00"
};
this.setState({ data });
}
render() {
const { data } = this.state;
return (
<div>
{Object.keys(data).map((key, index) => (
<p key={index}> value is {data[key]}</p>
))}
hello
</div>
);
}
}
export default A;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.