简体   繁体   English

在 setState 不起作用后,Reactjs 将值作为道具传递

[英]Reactjs pass value as prop after setState not working

I'm trying to pass down to a modal a object via a prop when a user clicks to open.当用户单击打开时,我试图通过道具将对象传递给模态。 I'm receiving the value from the clicked row but my modal can't read the value from this.props and I'm getting an undefined.我从被点击的行接收值,但我的模式无法从this.props读取值,我得到一个未定义的值。 I am setting the state value correctly and passing it to the modal component.我正在正确设置状态值并将其传递给模态组件。

Modal Call模态调用

<Modal toggleModal={this.toggleModal} show={this.state.isOpen}
          onClose={this.toggleModal} user={this.state.user} />

Setting the state value设置状态值

toggleModal = (user) => {
var userData = {};
if (user !== null) {
  userData = user
}
this.setState({
  isOpen: !this.state.isOpen,
  user: userData
},()=>{
  console.log('User data changed');
})
}

Inside the render part of the modal component在模态组件的渲染部分内部

if (this.props.user === null) {
  userFound = 'Not found'
}
console.log(this.props.user);

When inside the modal component I get undefined.在模态组件内部时,我未定义。 Everywhere before that I get the user object.在此之前的任何地方我都得到了用户对象。

Thanks谢谢

Inside your component you are just checking for null and not undefined , if you want to check for undefined one of the ways is to make use of typeof在您的组件内部,您只是检查 null 而不是undefined ,如果您想检查 undefined ,其中一种方法是使用typeof

typeof user !== "undefined"

so it will be like (You can ammend it accordingly if you want to check for both or one ):所以它会像(如果你想检查两者或一个,你可以相应地修改它):

toggleModal = (user) => {
  var userData = {};
  if (typeof user !== "undefined" && user !== null) {
  userData = user
}

And you can move this.setState inside if block你可以在 if block移动this.setState

toggleModal = (user) => {
    if (typeof user !== "undefined" && user !== null) {
      this.setState({
        isOpen: !this.state.isOpen,
        user: user
     })
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM