这段代码有什么问题吗?
class App extends React.Component {
constructor(props) {
super(props);
this.state ={
name: '',
gender: '',
age: '',
};
}
componentWillMount() {
const { steps } = this.props;
const { name, gender, age } =steps;
this.setState({ name, gender,age });
}
错误显示如下:
它不是在正上方的 this.state
block 中定义的吗?
完整代码在这里:
App.js
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
age: '',
};
}
componentWillMount() {
const { steps } = this.props;
const { name,age } = steps;
this.setState({ name, age });
}
render() {
const { name, age } = this.state;
return (
<div>
<h3>Summary</h3>
<table>
<tbody>
<tr>
<td>Name</td>
<td>{name.value}</td>
</tr>
<tr>
<td>Age</td>
<td>{age.value}</td>
</tr>
</tbody>
</table>
</div>
);
}
}
SimpleForm.js
const steps = [
{
id: '1',
message: 'What is your name?',
trigger: 'name',
},
{
id: 'name',
user: true,
trigger: '5',
},
{
id: '5',
message: 'How old are you?',
trigger: 'age',
},
{
id: 'age',
user: true,
trigger: '7',
},
{
id: '7',
message: 'Great! Check out your summary',
trigger: 'review',
},
{
id: 'review',
component: <App />,
asMessage: true,
end: true,
}
]
class simpleForm extends React.Component {
render() {
return (
<ChatBot steps={steps} />
)
}
}
export default simpleForm;
最佳答案
错误很明显。您没有向 App 组件发送任何 Prop ,因此 { steps } 是未定义的,并且您不能解构属性“steps”,因为它是未定义的。
关于reactjs - react 类型错误 : Cannot destructure property as it is undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62441256/