reactjs - react 类型错误 : Cannot destructure property as it is undefined

标签 reactjs components state react-props

这段代码有什么问题吗?

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 });

  }

错误显示如下:

enter image description here

它不是在正上方的 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/

相关文章:

javascript - 无法在客户端填充缩略图

javascript - 如何在基于类的组件中使用 React.forwardRef?

android - 属性委托(delegate)必须有一个 'getValue(Nothing?, KProperty*>)' 方法

javascript - 如何导航到新页面React Router v4

node.js - Heroku 上的空白应用程序 : express. 静态和/或 res.sendFile 问题?

javascript - 用 vanilla javascript 重写 React 功能组件

.net - 在 .NET 中使用 System.IO.Ports.SerialPort 驱动 DTR

javascript - 你如何命名用于 Vue.js 组件中的 exjection 的 Axios 拦截器?

angularjs - 可以从URL中获取参数