我有两个组件:Orders
和 FormDialog
,第一个组件是第二个组件的父组件。
我尝试将数据作为属性从 Orders
发送到 FormDialog
,如下所示:
Orders Component
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 Component
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
。有什么建议吗?
最佳答案
两个问题:
您的渲染方法正在尝试使用尚未初始化的状态渲染 FormDialog。状态将是未定义,直到您在构造函数中设置它,例如:
constructor(props) { super(props); this.state = { order: this.props.order, } }
由于您只是从父组件传递一个 prop,这足以渲染组件而不会出现错误。这样您就不需要调用componentDidMount,或者在您的情况下调用componentWillMount,并且可以将其完全删除。
<小时/>- 您在未挂载的组件中调用 setState,这始终会导致 React 出现错误。顾名思义,componentWillMount 在组件安装之前调用,您应该使用 componentDidMount 来确保在调用 setState 之前安装组件>.
此外,componentWillMount 在较新版本的 React 中已被弃用,不再建议在代码中使用。
From React official documentation
<小时/>附加说明,在我看来,这两个组件中存在不必要的状态重复。考虑仅将订单数据保留在 FormDialog 组件中,因为它可能是唯一更新订单数据的组件。
关于javascript - 从 props 中 react 未定义的 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55054643/