[英]React undefined setState from props
我有兩個組件: Orders
和FormDialog
,第一個是第二個的父親。 我試圖將數據作為屬性從Orders
發送到FormDialog
,如下所示:
訂單組件
class Orders extends Component {
state={
open: false,
order: {
address: '',
client: '',
date: '',
estimated_time: '',
id: 0,
order_no: '',
original_order_no: '',
phone: '',
place: '',
position: '',
status: '',
team: ''
}
}
render() {
return (
<div>
<FormDialog open={this.state.open} order={this.state.order}/>
</div>
);
}
FormDialog組件
export default class FormDialog extends React.Component {
constructor(...props) {
super(...props);
this.state = {
order: {
address: '',
client: '',
date: '',
estimated_time: '',
id: 0,
order_no: '',
original_order_no: '',
phone: '',
place: '',
position: '',
status: '',
team: ''
}
};
}
async componentWillMount()
this.setState({order: this.props.order})
};
render() {
return (
<div>{this.state.order.team}</div>
)}
嘗試編譯時,此顯示TypeError: this.state.order is undefined
。 有什么建議嗎?
兩個問題:
您的render方法正在嘗試使用尚未初始化的狀態來渲染FormDialog。 狀態將是不確定的,直到您在構造函數中將其設置為:
constructor(props) { super(props); this.state = { order: this.props.order, } }
由於您只是從父組件傳遞了一個prop,因此足以渲染該組件而不會出錯。 這樣,您無需調用componentDidMount ,也無需調用componentWillMount ,並且可以將其完全刪除。
另外,在較新版本的React中不建議使用componentWillMount ,因此不建議在代碼中使用它。
另外請注意,在我看來,您在這兩個組件中具有不必要的狀態重復。 考慮將訂單數據僅保留在FormDialog組件中,因為它可能是唯一更新訂單數據的組件。
super(props),而不是super(... props)與構造函數相同
此指向文檔的鏈接顯示了正確的方法
https://reactjs.org/docs/react-component.html#constructor
就在構造函數之后,代碼仍然是正確的,但是在componentWillMount state.order被this.props.order替換之后,由於第一個錯誤而未初始化。
您應該避免狀態重復,可以使FormDialog成為無狀態組件,甚至可以使函數組件成為無狀態。 記住要使用盡可能多的無狀態組件。
import React from 'react';
const FormDialog = props => {
return (
<div>
{props.order.team}
</div>
);
};
export default FormDialog;
無論如何,看起來是因為您出現TypeError錯誤
(1)錯字,應該是
constructor (props) {
super (props);
this.state = bla bla bla ...;
}
要不就
state= bla bla bla ...
就像您在“訂單”組件中所做的一樣
(2)在安裝組件之前嘗試調用setstate。 將異步componentWillMount()更改為componentDidMount()應該可以工作。
但是不必擔心,在將組件更改為功能組件后,它不應出現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.