React类型错误:无法解构未定义的属性

5

这段代码有问题吗?

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

完整代码如下:

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;

你的组件属性中定义了什么?或者更准确地说,this.props.steps 是什么样子的? - wentjun
@wentjun 这是聊天机器人的基本步骤,我想要在聊天机器人对话框中捕获用户输入(姓名、性别、年龄),并将它们呈现在屏幕上。聊天机器人组件参考自这里(https://lucasbassetti.com.br/react-simple-chatbot/#/docs/hello-world)。我回答了你的问题吗? - wflwo
2个回答

5
错误很明显。你没有向App组件发送任何props,所以{steps}是未定义的,你不能解构属性“steps”,因为它是未定义的。

0

componentWillMount 是一个已经被弃用的生命周期方法,将在 17 版本中被移除。React 文档

一种选择是从 props 中定义默认值到 state 中。

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

你也可以在componentDidMount之后设置它的状态。


当我改变为新状态时,render()函数可以正常工作,但是为什么{name.value}没有显示任何内容呢? - wflwo
你有完整的代码示例吗?这里那里的片段很难看出正在发生什么。 - michael.mcshinsky
当然会在原帖上添加 :D - wflwo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接