【问题标题】:React TypeError: Cannot destructure property as it is undefinedReact TypeError:无法解构属性,因为它未定义
【发布时间】:2020-10-07 23:53:33
【问题描述】:

这段代码有问题吗?

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 块中定义的吗?


完整代码在这里:

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;

【问题讨论】:

  • 组件的 props 中定义了什么?或者准确地说,this.props.steps 长什么样子?
  • @wentjun 这是聊天机器人的主要步骤,我想将用户输入((姓名、性别、年龄))捕捉到聊天机器人对话框中,并将它们呈现到屏幕上。聊天机器人组件从这里引用 (lucasbassetti.com.br/react-simple-chatbot/#/docs/hello-world)。我会回答你的问题吗?

标签: reactjs components state react-props


【解决方案1】:

错误很明显。您没有向 App 组件发送任何道具,因此 { steps } 未定义,并且您无法解构属性“steps”,因为它未定义。

【讨论】:

    【解决方案2】:

    componentWillMount 现在是一种已弃用的生命周期方法,将在版本 17 中删除。React Documentation

    一个选项是从 props 定义默认状态。 例如

    this.state = {
      name: this.props.steps.name || '',
      gender: this.props.steps.gender || '',
      age: this.props.steps.age || ''
    }
    

    您也可以将其设置为componentDidMount 之后的状态。

    【讨论】:

    • 当我进入新状态时工作,但是在 render() { const { name, gender, age } = this.state; return ( {name.value} ) } 什么都不显示?
    • 您有完整的代码示例吗?在这里和那里很难看到 sn-ps 发生了什么。
    • 肯定会添加到原帖中:D
    猜你喜欢
    • 1970-01-01
    • 2021-03-08
    • 2021-05-11
    • 2021-04-04
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多