反应TypeError:无法解构属性,因为它是未定义的

时间:2020-06-18 02:15:55

标签: 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块中定义了吗?


完整代码在这里:

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;

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

... void OnTick() { bool Order_close_result = false; ... Order_close_result = OrderClose(..., OrderClosePrice(), ...); //row1, close at market price ... if(Order_close_result) {...} //row2, to check if it is closed ... } 现在是不推荐使用的生命周期方法,将在版本17中删除。React Documentation

一个选项是将默认值定义为道具的状态。 例如

componentWillMount

您还可以将其设置为this.state = { name: this.props.steps.name || '', gender: this.props.steps.gender || '', age: this.props.steps.age || '' } 之后的状态。