javascript - React Native/React - 在 render() 之前重构 prop

标签 javascript reactjs react-native

我已经通过了guest对象作为一种属性从一个 View 到下一个 View 。 guest由各种属性组成 guest.name , guest.age , guest.email

位于将接收 guest 的 View 的类定义的开头我想从 this.props.guest.name 重构对象至guest.name所以我设置如下:

class EditGuest extends Component {
  const { guest } = this.props;
  state = {
    name: guest.name,
    email: guest.email,
    age: guest.age
  };

  render() {
    ...
    ...
    ...
    ...
}

export default EditGuest;

但是我收到错误 parsing error: unexpected token, expected '('对于我重构的行 const { guest } = this.props 。如果我定义 guest渲染函数中的对象可以正常工作,但在其外部定义时则不起作用。

这是怎么回事?

最佳答案

您应该将其写在构造函数中。类似于下面的内容

class EditGuest extends Component {
  constructor(props) {
   super(props);
   const { guest } = props;
   this.state = {
     name: guest.name,
     email: guest.email,
     age: guest.age
   };
  }

  render() {
    ...
    ...
    ...
    ...
  }
}
export default EditGuest;

关于javascript - React Native/React - 在 render() 之前重构 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40336240/

相关文章:

javascript - 使用replace从html中删除<strong>标签

javascript - fetch 向后端发送错误的数据格式

javascript - React API 处理 Fetch 调用中的错误 : TypeError-Cannot read property 'temp' of undefined

react-native - React Native 构建失败-(在项目 'RCT-Folly' 的目标 'Pods' 中)

javascript - 使用 jquery 将 ID 分配给 body 标签

javascript - 'package.json' 不在 'rootDir' 之下

javascript - 如何使用 WebStorm 中的内置 Web 服务器打开/调试当前文件?

reactjs - React 渲染 SVG 会覆盖页面上的其他 SVG

javascript - 循环中的 react-native-maps 标记未呈现

reactjs - 如何只发送图片消息? (也无需发送文本)